Consider a table A
with a primary key, column1, column2.
Now let column1 be the primary key which is of type uniqueidentifier
.
Now if you want to avoid duplicate inserts into the table using a stored procedure, which would be the better way?
Case #1:
IF NOT EXISTS (SELECT 1 FROM TABLE A WHERE column1 = @insertValue)
BEGIN
INSERT INTO Table A
....
END
or case #2:
TRY
BEGIN
INSERT INTO TABLE A
END
CATCH
BEGIN
IF(ErrorNumber() = 2627)--Erro number of primary key violation
BEGIN
---------- deal with the error
END
END
I feel case #2 is better, because only 1 time SQL check operation is done, but in case#1 it is happening 2 times.
I understand when we create a primary key on a table, SQL checks for duplicates before insert, using this existing mechanism of SQL check for duplication isn't it good? instead of using IF NOT EXISTS
Please add your answer, please explain the answer in depth considering all the parameters
Guys please help me in understanding in terms of sql operation on a table. Objective here is to understand the internal mechanism of sql primary key violation check,