Skip to content
Advertisement

Determine record exist by exception of SQL is Principles?

I have a table with primary key and I want to insert new record to that.

In my code, I check if record exists by exception. In the SQL stored procedure, I have insert code and surround by exception, in my application I execute that stored procedure and want to insert new record, if my record exist in table, insert code throws an error:

The INSERT statement conflicted with the FOREIGN KEY constraint “FK_Sup_Item_Sup_Item_Cat”. The conflict occurred in database test, table test. The statement has been terminated.

and goes to the catch block.

In my application I check the error that was returned by SQL, and it shows a message box to user that record is exist.

I want to know, is this way is Principles? or I must use if exist statement in SQL?

Advertisement

Answer

Exception should never be used when you can avoid it and return a value.
Exception is a “stress” on a system and much slower than any other way.

Its customary for a SP to return 0 if everything is Ok and a negative value if there is an error.
Either check your SP return code in application or use out parameter to determine problem. An error should be truly an error.

User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement