Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

T-SQL: Update column only if value is provided

Currently I have this UPDATE statement:

UPDATE Customer 
SET Name = @Name,
    Age = @Age,
    Email = @Email
    ...

Now I need to include column into the UPDATE statement only if value is provided. Otherwise, do not include the column in the UPDATE statement.

So conceptually probably something like this:

UPDATE Customer 
SET
    IF LEN(@Name) > 0 THEN Name = @Name,
    IF LEN(@Age) > 0 THEN Age = @Age,
    IF LEN(@Email ) > 0 THEN Email = @Email
    ...

Is there any way can achieve this? I'm thinking about dynamic query but the list of update columns are super long, so tons of work need to be done to change to dynamic query like this:

SET @SQL = 'UPDATE Customer SET '

IF LEN(@Name) > 0
    SET @SQL = @SQL + 'Name = @Name,'

IF LEN(@Age) > 0
    SET @SQL = @SQL + 'Age= @Age,'
like image 595
Koo SengSeng Avatar asked Oct 29 '25 14:10

Koo SengSeng


2 Answers

I think you should try this (after declaring and setting your variables @Name, @Age and @Email )

    UPDATE Customer SET
    Name = case when @Name  is null then Name  else @Name  end,
    Age  = case when @Age   is null then Age   else @Age   end,
    Email= case when @Email is null then Email else @Email end,
    ...

if any of the variables has a null value it will not update the field.

like image 99
Omar Hamdan Avatar answered Oct 31 '25 04:10

Omar Hamdan


What about something like this...

UPDATE Customer SET
    [Name] = CASE WHEN ISNULL(@Name, '') = '' THEN [Name] ELSE @Name END
    ,Age = CASE WHEN ISNULL(@Age, '') = '' THEN Age ELSE @Age END
    ,Email = CASE WHEN ISNULL(@Email, '') = '' THEN Email ELSE @Email END
    ...
like image 24
CSharp821 Avatar answered Oct 31 '25 04:10

CSharp821



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!