0

我正在编写一个带有两个参数的 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, where 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'sSuperceded应该被更新为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语句的值呢?insertupdateold_id

决赛桌应该是

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

我正在使用 MS SQL Server。

4

2 回答 2

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
于 2012-11-15T15:42:44.047 回答
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
于 2012-11-15T15:58:24.357 回答