Andna
Andna

Reputation: 6689

Checking sql constraints

I have a question about constraints in SQL, to be exact in transact-sql. I have a database for trips. I created a procedure for adding new trip participant. I am using ms-sql server so foreign key and primary key constraints were added when I created tables. Now in my procedure for adding new participant for a trip I have

insert VoyageThemes(VoyageId,ThemeId) values (@voyageId,@themeId)

now, in VoyageThemes table both VoyageId and ThemeId are primary keys and foreign keys, so when I try to add new values that doesen't correspond to already existing values in database constraint raises it's head.

My question is, can I somehow check if constraint 'said' that I can't add values to table, so I can stop the procedure or I need to manually check in my database if VoyageId and ThemeId exists.

I need to know if those values exists because of this line of code:

update Voyages
set Voyages.Price=Voyages.Price+@costOfTheme*@numOfParticipants

I am updating the price of a trip, so this line of code can only excecute only if there is a corresponding VoyageId and ThemeId

Upvotes: 1

Views: 166

Answers (2)

onedaywhen
onedaywhen

Reputation: 57093

Rather than INSERT, use MERGE to create a row only if it does not already exists e.g.

MERGE INTO VoyageThemes
   USING (
          VALUES (@voyageId, @themeId)
         ) AS S (VoyageId, ThemeId)
      ON VoyageThemes.VoyageId = S.VoyageId
         AND VoyageThemes.ThemeId = S.ThemeId
WHEN NOT MATCHED THEN
   INSERT (VoyageId, ThemeId)
      VALUES (VoyageId, ThemeId);

Upvotes: 1

gpeche
gpeche

Reputation: 22524

I guess you can use a try/catch?:

...
BEGIN TRY  
    insert VoyageThemes(VoyageId,ThemeId) values (@voyageId,@themeId)     
    -- If we are here, then the insert succeeded, proceed with the update
    update Voyages
    set Voyages.Price=Voyages.Price+@costOfTheme*@numOfParticipants
    ...
END TRY 
BEGIN CATCH  
    -- insert failed, check error
    SELECT @error_number = ERROR_NUMBER(),
           @error_severity = ERROR_SEVERITY(),
           @error_state = ERROR_STATE()  
    IF @error_number = 547
    -- constraint violation   
        BEGIN     
            PRINT '...'   
        END  
    ELSE 
        -- propagate error 
        BEGIN
            RAISERROR(@error_number, @error_severity, @error_state) WITH LOG   
        END 
END CATCH

Upvotes: 2

Related Questions