简体   繁体   English

UPDATE是否在SQL Server中逐列进行

[英]Does UPDATE happen column by column in SQL Server

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? 我的问题是,更新是否会逐列进行,以便我可以在第2列中成功获取更新的值? 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. 我无法编写两个单独的查询。

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. DBMS最有可能拉出该行,检查值,然后写入更改。 In SQL Server, I'd write it like this: 在SQL Server中,我会这样写:

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: 是否有不能以这种方式编写SQL的原因:

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

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM