我正在尝试创建一个存储过程,该过程可以根据团队的ID自动填充团队中的玩家列表。 我想要做的就是说每支球队有20名球员,他们的名字与球队名称相匹配,他们的姓氏应以“球员”开头,最后根据相关球队的数量结束。
First Name Surname TeamID
AFC Wimbledon Player1 1
AFC Wimbledon Player2 1
AFC Wimbledon Player3 1
--All the way to 20 players
Angers Player1 2
我不知道如何做到这一点,需要很少的指导或代码示例,所以我可以看看它是如何完成的。我以为我可能需要一个OUTPUT来帮助解决这个问题,但我认为我的逻辑非常缺陷。 以下是表格: 队:
TeamID TeamName
1 AFC Wimbledon
2 Angers
3 Ards
播放器(当前为空时需要将其插入:
PlayerID FirstName Surame TeamID
以下是我的PROC:
CREATE PROCEDURE [dbo].[Player_Insert]
@FirstName VARCHAR(25) OUTPUT,
@Surname VARCHAR(25) OUTPUT,
@TeamName VARCHAR(50)
AS
SET NOCOUNT ON
BEGIN
DECLARE @TeamID INT, @CountPlayers INT
SELECT @TeamID = TeamID FROM Team WHERE TeamName = @TeamName
SELECT @CountPlayers = count(*) FROM Player WHERE TeamID = @TeamID
IF @CountPlayers >= 20
BEGIN
RAISERROR('Reached the maximum limit of players for %s', 16, 1, @TeamName);
RETURN;
END
SET @FirstName = @TeamName
SET @Surname = 'Player' + @CountPlayers
INSERT INTO Player (FirstName, Surname, TeamID)
VALUES (@FirstName, @Surname, @TeamID)
END
以下是EXEC PROC:
DECLARE @FirstNameOutput VARCHAR(25)
DECLARE @SurnameOutput VARCHAR(25)
EXEC Player_Insert
@FirstName = @FirstNameOutput OUTPUT,
@Surname = @SurnameOutput OUTPUT,
@TeamId = 1
答案 0 :(得分:0)
答案 1 :(得分:0)
这可以满足您的需求。
;WITH TallyTable
AS (
SELECT TOP 20 ROW_NUMBER() OVER (
ORDER BY a.id
) AS N
FROM Master.dbo.SysColumns a
,Master.dbo.SysColumns b
)
INSERT INTO Player (FirstName, Surname, TeamID)
SELECT TeamName AS FirstName
,'Player' + CAST(N AS VARCHAR(2)) AS Surname
,TeamID
FROM Team
CROSS JOIN TallyTable
ORDER BY TeamID, N