Shaggy
Shaggy

Reputation: 5790

Update column using case expression sql

I want to set column value only if it is not blank.

Here is sample

Declare @Temp Varchar(20)

Update Logins
Set ColValue = 
Case When @Temp <> '' Then @Temp Else /* Dont SET Value */ End
Where Code=1

What to write in Else Part ?

I have multiple columns to update and want to apply condition in only single column

DB : SQL SERVER 2008

Upvotes: 3

Views: 762

Answers (2)

Robert
Robert

Reputation: 25753

You have to set the updated column as below:

Declare @Temp Varchar(20)

Update Logins
Set ColValue = Case When @Temp <> '' Then @Temp 
                    Else ColValue 
               End
Where Code=1

Upvotes: 3

Nenad Zivkovic
Nenad Zivkovic

Reputation: 18559

You can check your variable in WHERE to not update at all when it's blank

Declare @Temp Varchar(20)

Update Logins
Set ColValue = @Temp
Where Code=1 AND @Temp <> ''

Upvotes: 0

Related Questions