如何在更新期间访问子查询中变量的新值

时间:2015-04-02 20:47:00

标签: sql sql-server tsql sql-update

在以下示例中:

create table #temp (col1 int, col2 int, col3 int)

declare @var int = 10

insert into #temp values(1, 2, 2)
insert into #temp values(2, 4, 4)
insert into #temp values(3, 6, 6)

update T set 
@var = 100,
col2 = @var * col2,         -- here @var yields 100, cool
col3 = (select @var * col3) -- but here it's value will be 10
from #temp T

select * from #temp

drop table #temp

col2的值乘以100,col3的值乘以10,如评论所示。 为什么会这样?

我需要访问子查询中变量的较新值。我会用更复杂的代码执行此操作,实际上是在where子句中(类似于:where @var = 4)。

2 个答案:

答案 0 :(得分:0)

只需使用两个变量:

declare @var2 int = 2;
declare @var4 int = 4;

update T set 
col2 = @var2 * col2,
col3 = @var4 * col3
from #temp T

答案 1 :(得分:0)

我明白了。当您使用SELECT @var时,它会抓取旧版本的变量(10值)。所以我将它移到select语句之外,它完美地运行。试试吧:

create table #temp (col1 int, col2 int, col3 int)

declare @var int = 10

insert into #temp values(1, 2, 2)
insert into #temp values(2, 4, 4)
insert into #temp values(3, 6, 6)

update T 
set @var = 100,
col2 = @var * col2,         -- here @var yields 100, cool
col3 = @var * (SELECT col3) --notice @var is outside select clause
from #temp T

select * from #temp

drop table #temp

结果:

col1        col2        col3
----------------------------
1           200         200
2           400         400
3           600         600