How to update T-SQL record and ignore UPDATE by parameters, where NULL

Is there a way to create an UPDATE stored_procedure with parameters such as:

@param1 int = null, @param2 int = null, @param3 nvarchar(255) = null, @param4 bit = null, @id int 

and with an UPDATE statement that will only update fields that are not NULL

so if i do

 spUpdateProcedure @param1=255, @id=1 

if the @id = 1 record is updated, but it only changes the @ param1 field and ignores the changes in another @ param2,3,4 parameter.

In other words, it will not change the value for null in @ param2,3,4

Thanks.

+4
source share
2 answers
 UPDATE YourTable SET Column1 = COALESCE(@param1, Column1), Column2 = COALESCE(@param2, Column2), ... WHERE id = @id 
+5
source

in your editor, you can do it

 update table set column1 = isnull(@param1,column1), column2 isnull(@param2,column2) 
0
source

All Articles