Constraints check: TRY/CATCH vs Exists()

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

    Option - 3

    Begin Try
        SET XACT_ABORT ON
        Begin Tran
            IF NOT EXISTS (Select 1 From MyTab Where SomeValue = @someValue)
            Begin
                Insert Into MyTab(SomeValue) Values ('aaa');
            End
        Commit Tran
    End Try
    
    begin Catch
        Rollback Tran
    End Catch
    

提交回复
热议问题