I’m trying to create a stored procedure that is automatically able to populate a list of players in a team based on the team’s ID. What I’m trying to do is say that each team has 20 players, their first name matches the team name and their surname should begin with ‘Player’ and end with a number based on a count for the relevant team e.g.
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
I am not sure how to do this and need little guidance or a code sample so I can look to see how it’s done. I thought I may need an OUTPUT to help solve this but I think my logic is terribly flawed. Here are the tables: Team:
TeamID TeamName
1 AFC Wimbledon
2 Angers
3 Ards
Player (currently empty as need this to be inserted to:
PlayerID FirstName Surame TeamID
Below is my PROC currently:
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
Below is the EXEC PROC:
DECLARE @FirstNameOutput VARCHAR(25)
DECLARE @SurnameOutput VARCHAR(25)
EXEC Player_Insert
@FirstName = @FirstNameOutput OUTPUT,
@Surname = @SurnameOutput OUTPUT,
@TeamId = 1