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,'
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.
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
...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With