2

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?

1 Answer 1

3

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.

Sign up to request clarification or add additional context in comments.

1 Comment

James thanks for this solution, it looks very easy solution to implement the only issue is that for large tables we need to create so many extra parameters in update Stored Procedures but so far this is the best solution I have until unless someone else came with another solution. Thanks once again.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.