Constraints check: TRY/CATCH vs Exists()

后端 未结 5 1831
面向向阳花
面向向阳花 2020-12-11 16:55

I have a table with unique constraint on it:

create table dbo.MyTab
(
    MyTabID int primary key identity,
    SomeValue nvarchar(50)
);
Create Unique Index          


        
5条回答
  •  甜味超标
    2020-12-11 17:31

    Error logging

    Don't hold me for this but there are likely logging implications when an exception is thrown. If you check before inserting no such thing happens.

    Knowing why and when it can break

    try/catch block should be used for parts that can break for non-deterministic reasons. I would say it's wiser in your case to check existing records because you know it can break and why exactly. So checking it yourself is from a developer's point of view a better way.

    But in your code it may still break on insert because between the check time and insert time some other user inserted it already... But that is (as said previously) non-deterministic error. That's why you:

    1. should be checking with exists
    2. inserting within try/catch

    Self explanatory code

    Another positive is also that it is plain to see from the code why it can break while the try/catch block can hide that and one may remove them thinking why is this here, it's just inserting records...

提交回复
热议问题