'Update specific columns in SQL Server table and ignoring Null values
I have a database table with many columns. Is there sql that will update records in that table where all or only specific columns are handled in such a way that if NULL is passed for any column value that the existing value not be changed?
Currently I can use solutions like these
UPDATE table
SET column1 = COALESCE(@param1, column1),
column2 = COALESCE(@param2, column2),
...
WHERE id = @id
or
UPDATE table
set column1 = isnull(@param1,column1),
column2 = isnull(@param2,column2)
They both works well, though sometimes I want to explicitly save null in any column and I can't do it with the above solutions. How?
Solution 1:[1]
One approach is to declare two parameters for each column, the first contains the value, the second is a bit instructs the query to insert null explicitly.
Example
create table example (column1 nvarchar(255), column2 nvarchar(255))
create procedure pUpdate(
@column1 nvarchar(255) = null,
@nullColumn1 tinyint = 0,
@column2 nvarchar(255) = null,
@nullColumn2 tinyint = 0
) as
BEGIN
update example
set column1 = Case When @nullcolumn1 = 1
Then NULL ELSE IsNull(@column1, column1) End
set column2 = Case When @nullcolumn2 = 1
Then NULL ELSE IsNull(@column2, column2) End
END
Then when calling from code, you only have to pass the parameters that you know need updating, or explicitely set the @nullcolumn to force a null.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | ΩmegaMan |
