Thread: FK Checks
View Single Post

   
  #4 (permalink)  
Old 02-28-2008, 07:09 PM
Erland Sommarskog
 
Posts: n/a
Default Re: FK Checks

Jason (JayCallas@hotmail.com) writes:
> I should have been more explicit in my question. I was referring to
> performing checks within stored procedures.
>
> Assuming Table2 has a FK relationship with Table1.
>
> IF EXISTS (SELECT * FROM Table1 WHERE Table1.Field1 = @field1)
> INSERT INTO Table2 (@field1, @field2, field3)
>
> as opposed to
>
> INSERT INTO Table2 (@field1, @field2, field3)
> IF @@Error RAISERROR('Unable to insert into Table2 because of missing
> constraint', 15, 1)


Again it depends. Say that your procedure is to be called from a GUI. In
this case you can presume that the GUI gets the information from the
databaes, and a foreign-key violation could only occur if the GUI is
incorrect. On the other hand, say that you are accepting data from an
external source over which you have no control. In this case, it is better
to check explicitly, so that you can log incorrect data appropriately.
Recall that when a constraint blows up, you cannot in T-SQL determine
which constraint that fired.


--
Erland Sommarskog, SQL Server MVP, sommar@algonet.se

Books Online for SQL Server SP3 at
http://www.microsoft.com/sql/techinf...2000/books.asp
Reply With Quote