SQL Stored Procedure: If variable is not null, update statement

前端 未结 3 1847
孤街浪徒
孤街浪徒 2021-02-05 05:53

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 t

3条回答
  •  旧巷少年郎
    2021-02-05 06:16

    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.

    select COALESCE(null, null, 1, 'two') --returns 1
    select COALESCE(null, null, null, 'two') --returns 'two'
    

提交回复
热议问题