如何从select中获取值并将其用作sql中的变量?
我正在编写一个带有两个参数的sql过程:@id和@id\u组 考虑此表如何从select中获取值并将其用作sql中的变量?,sql,sql-server,stored-procedures,Sql,Sql Server,Stored Procedures,我正在编写一个带有两个参数的sql过程:@id和@id\u组 考虑此表group\u info ID ID_Group SupercededBy Superceded status 1 1 null null H 2 1 null null U 考虑到这些参数: @id=2 @id_组=1 我需要做的第一件事是将行的替换为@id,其中id=@id和id\
group\u info
ID ID_Group SupercededBy Superceded status
1 1 null null H
2 1 null null U
考虑到这些参数:
@id=2
@id_组=1
我需要做的第一件事是将行的替换为@id
,其中id=@id和id\u组=@id\u组和status='H'
以下是我写的声明:
update group_info
set supercededby = @id
where id_group=@id_group and status='H'
第二件事
我需要做的是将行的被取代
设置为id
,其被取代的刚刚从上述语句中更新
因此,在本例中,行2
的被取代的应更新为1
但是如何编写语句呢?我猜语句可能是这样的:
update group_info
set superceded = **old_id**
where id=@id
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
我知道如何获取旧id
,在这里
select id
from group_info
where id_group=@id_group and status='H'
但是如何使用上述选择和插入语句中的值作为旧id
?
最后一张表应该是
ID ID_Group SupercededBy Superceded status
1 1 2 null H
2 1 null 1 U
我使用的是MS SQL Server。一个SELECT@variable=columnName FROM…
语句可以这样使用:
update group_info
set superceded = **old_id**
where id=@id
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
SELECT@variable=columnName FROM…
语句可以这样使用:
update group_info
set superceded = **old_id**
where id=@id
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
根据这个定义
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
根据这个定义
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
如果组具有更多ID,则最新选定的ID将用作@oldId。如果组具有更多ID,则最新选定的ID将用作@oldId。