Sql Stored Procedure: If Variable Is Not Null, Update Statement
I have an update statement in a stored procedure that looks generally like this: Update [TABLE_NAME] Set XYZ=@ABC Is there a good way to only trigger the update statement if the v
Solution 1:
Use a T-SQL IF
:
IF @ABCISNOTNULLAND@ABC!=-1UPDATE [TABLE_NAME] SET XYZ=@ABC
Take a look at the MSDN docs.
Solution 2:
Another approach when you have many updates would be to use COALESCE:
UPDATE [DATABASE].[dbo].[TABLE_NAME]
SET
[ABC] =COALESCE(@ABC, [ABC]),
[ABCD] =COALESCE(@ABCD, [ABCD])
Solution 3:
Yet another approach is ISNULL().
UPDATE [DATABASE].[dbo].[TABLE_NAME]
SET
[ABC] = ISNULL(@ABC, [ABC]),
[ABCD] = ISNULL(@ABCD, [ABCD])
The difference between ISNULL and COALESCE is the return type. COALESCE can also take more than 2 arguments, and use the first that is not null. I.e.
selectCOALESCE(null, null, 1, 'two') --returns 1selectCOALESCE(null, null, null, 'two') --returns 'two'
Post a Comment for "Sql Stored Procedure: If Variable Is Not Null, Update Statement"