Re: FK Checks Erland Sommarskog <sommar@algonet.se> wrote in message news:<Xns944C1D0487E5Yazorman@127.0.0.1>...
> Depends on business requirements. Basically, Fkeys is the database's
> mean of protection against bad data. If the user interface does not
> perform any checks itself, and relies on the database, you may avoid
> integrity violations, but the users may not get adequate error message.
>
> The way I see database constraints constitutes an inner defense line.
> The user interface should help the user, and have its own defense line.
> Error messages from the database exposed to the user, should be considered
> a bug.
>
> But validation in a GUI, can be quite different from the validation in
> SQL Server. Normally you don't let the user to type in the FK as free-
> text, but you let him choose from a drop-down box or from a search screen.
> Once you know, the user has selected data this way, you can assume that
> you are safe. (Although, someone may delete the row before the users
> saves.)
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) |