vim
vim

Reputation: 874

Compare two SQL Server columns with a value and insert output in third column

I have two columns WL-Value and RF-Value, if both have any value then we have insert value in third column "Final". If those any columns have 0 or null value then only need to take column heading text which column have value.

I need query for inserting value in "Final" column after comparing WL-Value and RF-Value according to their values.

------------------------------------------------------------------------  
ID   |    WL-Value      |            RF-Value        |        Final    |
------------------------------------------------------------------------
1         0                           243000                    RF
2        254365                        0                        WL
3        2478954'                     2874269                   RF,WL
4         0                             0                       Null
5        Null                           0                       Null

Query require for "Final" column after checking other two columns

Upvotes: 0

Views: 919

Answers (2)

Felix Pamittan
Felix Pamittan

Reputation: 31879

You can use CASE expressions with the help of STUFF for formatting:

UPDATE tbl
SET Final = STUFF((
                CASE WHEN ISNULL([RF-Value], 0) > 0 THEN ',RF' ELSE '' END +
                CASE WHEN ISNULL([WL-Value], 0) > 0 THEN ',WL' ELSE '' END 
            ), 1, 1, '')

Upvotes: 1

Rahul Tripathi
Rahul Tripathi

Reputation: 172448

Try this:

update tablename
set [Final] =  case when  ([WL-Value] = 0 or [WL-Value] is null) and (([RF-Value] <> 0 or [RF-Value] is not null)) then 'RF'
                    when  ([WL-Value] <> 0 or [WL-Value] is not null) and (([RF-Value] = 0 or [RF-Value] is null)) then 'LF'
              else 'Null' end

Upvotes: 1

Related Questions