Constraints check: TRY/CATCH vs Exists()

后端 未结 5 1830
面向向阳花
面向向阳花 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:45

    I've seen that article but note that for low failure rates I'd prefer the "JFDI" pattern. I've used this on high volume systems before (40k rows/second).

    In Aaron's code, you can still get a duplicate when testing first under high load and lots of writes. (explained here on dba.se) This is important: your duplicates still happen, just less often. You still need exception handling and knowing when to ignore the duplicate error (2627)

    Edit: explained succinctly by Remus in another answer

    However, I would have a separate TRY/CATCH to test only for the duplicate error

    BEGIN TRY
    
    -- stuff
    
      BEGIN TRY
         INSERT etc
      END TRY
      BEGIN CATCH
          IF ERROR_NUMBER() <> 2627
            RAISERROR etc
      END CATCH
    
    --more stuff
    
    BEGIN CATCH
        RAISERROR etc
    END CATCH
    

提交回复
热议问题