2

我有 2 个表 Winner 和 player ,包含标准信息(姓氏、名字、ID ...)加上两个布尔列 Validity 和 WinnerState(默认为 0)。

我想要做的是创建一个 SQL Server 过程,它将从玩家表中随机选择一条记录,然后将其插入到获胜者表中,并同时更新玩家表中选择的记录的获胜者状态列。

获胜者表包含玩家的外键,以跟踪所选玩家。

我已经尝试过一个程序,但它会为所有玩家表更新此列:

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

如何让它只更新随机选择的记录?谢谢!

4

2 回答 2

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
于 2013-07-30T21:16:41.040 回答
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
于 2013-07-30T21:07:30.973 回答