Question

I have following query -

 UPDATE THINGS

SET Col 1 = CASE when 'A' then 'APPLE'
                 when 'B' then 'BALL'
                 when 'C' then 'CARROT'
                 else NULL
                 end,
    Col 2 = Case Col 1 when 'APPLE' then 'FRUIT'
                       when 'BALL'  then 'TOY'
                       when 'CARROT' then 'SALAD'
             else NULL
             end

My question is will the update happen on column by column basis so that I can get updated values in my Col 2 successfully? If it is not possible by above query, is there any other way to update it within a single query? I cannot write two separate queries.

Was it helpful?

Solution

You can use this approach by using variable to store data and then use it foe next column.

DECLARE @val VARCHAR(20) -- type of Col1
UPDATE THINGS
SET @val = [Col 1] = CASE WHEN 'A' THEN 'APPLE'
                          WHEN 'B' THEN 'BALL'
                          WHEN 'C' THEN 'CARROT'
                     END,
       [Col 2] = CASE @val WHEN 'APPLE'  THEN 'FRUIT'
                           WHEN 'BALL'   THEN 'TOY'
                           WHEN 'CARROT' THEN 'SALAD'
                 END

OTHER TIPS

You can't rely upon the order of execution of assignments in a query. Most likely, the DBMS will pull the row, check the values, then write the changes. In SQL Server, I'd write it like this:

UPDATE THINGS
SET [Col 1] = CASE WHEN [Col 1] = 'A' then 'APPLE'
             WHEN [Col 1] = 'B' then 'BALL'
             WHEN [Col 1] = 'C' then 'CARROT'
             ELSE NULL
             END,
    [Col 2] = CASE WHEN [Col 1] IN ('A','APPLE') then 'FRUIT'
             WHEN [Col 1] IN ('B', 'BALL')  then 'TOY'
             WHEN [Col 1] IN ('C','CARROT') then 'SALAD'
             ELSE NULL
             END

Is there a reason you cannot write your SQL this way:

UPDATE THINGS
SET Col1 = CASE col1
             when 'A' then 'APPLE'
             when 'B' then 'BALL'
             when 'C' then 'CARROT'
             else NULL
             end,
Col2 = Case Col1
            when 'A' then 'FRUIT'
            when 'B' then 'TOY'
            when 'C' then 'SALAD'
         else NULL
         end

Actually, the columns are logically updated in their order in the update statement.

Here's a little sample to demonstrate it:

create table #t (i int, j int);
go
insert #t values (1,10);
go

update #t 
set j = i,
i = 5;

select * from #t;
go

drop table #t;
go
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top