我有2个表Winner和player,包含标准信息(姓氏,名字,ID ......)以及两个布尔列Validity和WinnerState(默认为0)。
我想要做的是创建一个SQL Server程序,它将从Players Table中随机选择一条记录,然后将其插入Winner Table并同时更新在播放器Table中选择的记录的WinnerState列。 / p>
Winner表包含播放器的外键,以便选择此播放器的跟踪。
我已经尝试过一个程序,但它会为所有玩家表更新此列:
create procedure selectUpdate
As
insert into Winner (Fname,Lname,Adress,City,Tel,Player_ID) from
select TOP 1 (Fname,Lname,Adress,City,Tel,ID) from Player order by NEWID()
Update Player
SET WinnerState=1
我可以让它只更新随机选择的记录吗?谢谢!
答案 0 :(得分:3)
您可以在一个声明中完成所有操作:
create procedure selectUpdate
as
begin
set nocount on
;with p as (
select top 1 Fname,Lname,Adress,City,Tel,ID,WinnerState
from Player
where WinnerState = 0 -- this is necessary I assume
order by checksum(NEWID())
)
update p
set WinnerState = 1
output
inserted.Fname,
inserted.Lname,
inserted.Adress,
inserted.City,
inserted.Tel,
inserted.ID into Winner (Fname,Lname,Adress,City,Tel,Player_ID)
end
答案 1 :(得分:2)
假设ID是INT并且是Player表的主键:
DECLARE @id INT
SELECT TOP 1 @id = ID FROM Player ORDER BY NEWID()
insert into Winner (Fname,Lname,Adress,City,Tel,Player_ID) from
select Fname,Lname,Adress,City,Tel,ID from Player WHERE ID = @id
Update Player
SET WinnerState=1 WHERE ID = @id