How to check if value is inserted successfully or not?

前端 未结 4 902
栀梦
栀梦 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 17:49

    You can use @@ROWCOUNT server variable immediately after the insert query to check number of affected rows by the insert operation.

    declare @fName varchar(50) = 'Abcd',
            @lName varchar(50) = 'Efgh'
    INSERT INTO myTbl(fName,lName) values(@fName,@lName)
    
    PRINT @@ROWCOUNT --> 0- means no rows affected/nothing inserted 
                     --> 1- means your row has been inserted successfully 
    

    For your requirement, you could use a Case statement(as per comment):

    --If you need @check as a bit type please change Int to bit
    DECLARE @check Int = CASE WHEN @@ROWCOUNT = 0 THEN 1 ELSE 0 END
    

提交回复
热议问题