2012-11-15 32 views
0

我正在寫一個帶有兩個參數的sql proc:@id和@id_group。如何從select中獲取值並將其用作sql中的變量?

考慮這個表group_info

ID ID_Group SupercededBy Superceded status 
1 1   null   null   H 
2 1   null   null   U 

考慮到這些參數:

@id = 2 @id_group = 1

The first thing我需要做的是設置行的SupercededBy@id,其中[email protected] and [email protected]_group and status='H'

這是我寫的語句:

update group_info 
     set supercededby = @id 
     where [email protected]_group and status='H' 

The second thing我需要做的是設置行的Superceded到其SupercededBy已經剛剛從上述表述的更新id

所以在這個例子中,row 2Superceded應該更新爲1

但是如何編寫語句?我想聲明可能是這樣的:

update group_info 
     set superceded = **old_id** 
     where [email protected] 

我知道如何讓old_id,這裏是

select id 
    from group_info 
    where [email protected]_group and status='H' 

但我怎麼可以在上面selectinsert使用的值update報表的值爲old_id

最後的表應該是

ID ID_Group SupercededBy Superceded status 
1 1   2    null   H 
2 1   null   1   U 

我使用MS SQL Server中。

回答

3

一個SELECT @variable = columnName FROM ...語句可以像這樣使用:

DECLARE @oldId INT 

select @oldId = id 
    from group_info 
    where [email protected]_group and status='H' 

update group_info 
     set superceded = @oldId 
     where [email protected] 
+0

是啊,它的工作。謝謝 –

+0

@JacksonTale我希望它!:) –

+0

如果該組遇到多個ID,會發生什麼情況... – bummi

0

這一定義

The second thing I need to do is to 
set the row’s Superceded to the id whose SupercededBy has been 
just updated from the above statements. 

這是一個massoperation

update group_info 
set supercededby = @id 
where [email protected]_group and status='H' 


Select ID,supercededby 
into #tmp 
from group_info 
where [email protected]_group and status='H' 



update group_info 
set superceded = #tmp.ID 
from #tmp 
where group_info.ID=#tmp.supercededby 

Drop table #tmp 
相關問題