2015-04-02 56 views
2

在下面的例子:如何更新期間訪問變量的新值的子查詢內部

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)。

回答

0

只要使用兩個變量:

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

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

其實我爲什麼要使用一個變量的唯一原因是,它的價值是從另一個子查詢(順便說一句漂​​亮的巨大)的結果。它的值將在更新中多次使用,所以我不想多次重複子查詢。 – 2015-04-02 21:04:34

+0

您可以執行一次子查詢並初始化變量,然後使用第一個變量初始化第二個變量? – gotqn 2015-04-02 21:11:39

+0

子查詢使用正在更新的行的值,所以,nope – 2015-04-02 21:20:58

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 
+0

確實,但你有什麼線索爲什麼? – 2015-04-22 15:36:43

+0

這只是SQL Server運行查詢的方式。當你把這個變量放在select語句中時,它顯然會抓住變量的一個老版本。對不起,希望我能有更多的幫助,但至少它的作用是對的? – Stephan 2015-04-22 17:46:58