I have a stored procedure that will INSERT a record into a table. I have created a unique key constraint on the table to avoid duplicate records.
Regardless of the fact that there is a unique key constraint defined, I am using an IF() condition (prior to the INSERT statement) to check for a duplicate record that may already exist.
However, the conditional statement that I am using to check for a duplicate record is seemingly having no affect on whether or not the INSERT is executed. - i.e. when a duplicate record in submitted to the sproc, a "Violation of UNIQUE KEY constraint..." exception is thrown.
Here is a sample of my sproc:
BEGIN
if
(SELECT Count(f1)
FROM table
WHERE f1 = @f1
AND f2= @f2)
<= 0
BEGIN
INSERT INTO table
(f1,f2)
VALUES
(@f1, @f2)
RETURN @@IDENTITY
END
END
Is there something wrong with my syntax? Or, maybe, I'm going about this the wrong way?