需要帮助理解UPDATE ... FROM

时间:2010-09-13 15:53:07

标签: sql-server sql-server-2005 tsql

请帮助我了解T-SQL UPDATE FROM查询的工作原理。下面的示例查询结果为

value-inc, value-dec
value-inc, value-dec
value-inc, value-dec
value-inc, value-dec
value-inc, value-dec
value-inc, value-dec

我期待这个:

null,        'value-dec'
null,        'value-dec'
null,        'value-inc'
null,        'value-inc'
null,        null
'value-inc', 'value-dec'
我错在哪里? 谢谢 康斯坦丁


declare @t table (s1 varchar(10), s2 varchar(10));

insert into @t
select null, null
union all
select null, null
union all
select null, null
union all
select null, null
union all
select null, null
union all
select null, null;

update @t
set s1 = x.s1, s2 = x.s2
from (select null as s1, 'value-dec' as s2
      union all
      select null as s1, 'value-dec' as s2
      union all
      select null as s1, 'value-inc' as s2
      union all
      select null as s1, 'value-inc' as s2
      union all
      select null as s1, null as s2
      union all
      select 'value-inc' as s1, 'value-dec' as s2) as x;

select * from @t;

2 个答案:

答案 0 :(得分:1)

Ben Robinson's answer中所述,您需要两个表之间的公共值才能以您期望的方式执行更新。我已经更新了您的原始示例,在表中添加了一个id列。然后将该id用作更新的连接条件,如下面的代码所示。希望这个例子可以让你更清楚。

declare @t table (id int identity, s1 varchar(10), s2 varchar(10));

insert into @t
select null, null
union all
select null, null
union all
select null, null
union all
select null, null
union all
select null, null
union all
select null, null;

update t
set s1 = x.s1, s2 = x.s2
from @t as t
inner join (select 1 as id, null as s1, 'value-dec' as s2
            union all
            select 2 as id, null as s1, 'value-dec' as s2
            union all
            select 3 as id, null as s1, 'value-inc' as s2
            union all
            select 4 as id, null as s1, 'value-inc' as s2
            union all
            select 5 as id, null as s1, null as s2
            union all
            select 6 as id, 'value-inc' as s1, 'value-dec' as s2) as x
on t.id = x.id;

select * from @t;

答案 1 :(得分:0)

更新仅允许您构建一组联接以定义要更新的内容,方法与您选择的方式相同。 e.g。

update t1
set t1.SomeField=t2.SomeDield
from Table1 t1
inner join table2 t2 on t1.id=t2.id

在您的示例中,它不会真正起作用,因为无法将子查询连接到表变量。