How to check if value is inserted successfully or not?

前端 未结 4 775
栀梦
栀梦 2021-02-01 17:16

I have a procedure where I insert values into my table.

declare @fName varchar(50),@lName varchar(50),@check tinyint
INSERT INTO myTbl(fName,lName) values(@fName         


        
4条回答
  •  走了就别回头了
    2021-02-01 18:04

    You need to use @@ROWCOUNT

    It returns the number of rows affected by the last statement. If the number of rows is more than 2 billion, use ROWCOUNT_BIG.

    @@ROWCOUNT is both scope and connection safe.

    In fact, it reads only the last statement row count for that connection and scope.

    It’s safe to use @@ROWCOUNT in SQL Server even when there is a trigger on the base table. The trigger will not skew your results; you’ll get what you expect. @@ROWCOUNT works correctly even when NOCOUNT is set.

    so you query should be:

    declare @fName varchar(50), @lName varchar(50), @check tinyint = 0
    ...
    INSERT INTO myTbl(fName,lName) values(@fName,@lName)
    if  @@ROWCOUNT>0   
      set @check = 1
    

提交回复
热议问题