如何从select中获取值并将其用作sql中的变量?

时间:2012-11-15 15:37:25

标签: sql sql-server stored-procedures

我正在编写一个带有两个参数的sql proc:@id和@id_group。

考虑此表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,其中ID=@id and id_group=@id_group and status='H'

以下是我写的陈述:

  update group_info
      set supercededby = @id
      where id_group=@id_group and status='H'

The second thing我需要做的是将行的Superceded设置为idSupercededBy刚刚从上述语句中更新过来。

因此,在此示例中,row 2的{​​{1}}应更新为Superceded

但是如何编写语句?我猜这些语句可能是这样的:

1

我知道如何获取update group_info set superceded = **old_id** where id=@id ,这里是

old_id

但是,如何将上述select id from group_info where id_group=@id_group and status='H' select insert语句中的值用作update

决赛桌应为

old_id

我正在使用MS SQL Server。

2 个答案:

答案 0 :(得分:3)

SELECT @variable = columnName FROM ...语句可以像这样使用:

DECLARE @oldId INT

select @oldId  = id
    from group_info
    where id_group=@id_group and status='H'

update group_info
      set superceded = @oldId 
      where id=@id

答案 1 :(得分: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.

这是一场大规模的行动

update group_info
set supercededby = @id
where id_group=@id_group and status='H'


Select ID,supercededby  
into #tmp
from group_info
where id_group=@id_group and status='H'



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

Drop table #tmp