Max Taylor-Hayden
Max Taylor-Hayden

Reputation: 170

Insert into using a Case Statement

I am trying to insert data into a table using a stored procedure with one parameter. The parameter is looking for the name of a club. I want the SP to find all the players that belong to the club and insert them into the ClubNameTable. The problem is when I run the SP it inserts all the data from the join into the table, not just when the case statement is true.

CREATE PROCEDURE SSIS.usp_ClubNameTable 
    -- Add the parameters for the stored procedure here
    @NameOfClub nvarchar(200)
AS
BEGIN
    TRUNCATE TABLE SSIS.ClubNameTable;
    insert into ssis.ClubNameTable ([NameOfClub], [FirstName], [LastName])
        SELECT
            p.FirstName,
            COUNT(p.LastName) as 'Number of Last Names',                
            CASE
                WHEN @NameOfClub = 'Eagle Plate' THEN NameOfClub
                WHEN @NameOfClub = 'Atlanta United FC' THEN NameOfClub
                    ELSE 'Please choose either Eagle Plate or Atlanta United FC'
                end
    FROM [Location].Club as C
            JOIN [Location].ClubDetails as CD on c.ClubID = cd.ClubID
            JOIN [Player].Player as P on CD.PlayerID = P.PlayerID
            GROUP BY c.NameOfClub, p.FirstName, p.LastName
            ORDER BY p.LastName ASC
        declare 
        @RowCount int
            SET @RowCount = (SELECT COUNT(*) FROM Location.Club)
END
GO

Upvotes: 0

Views: 1298

Answers (1)

Amir Molaei
Amir Molaei

Reputation: 3820

Using case statement on a column does not do any filtering on records, it just applies conditions on the value that is to be assigned to the column. In order to filter records you need to use a where clause with the desired conditions:

 CREATE PROCEDURE SSIS.usp_ClubNameTable 
    -- Add the parameters for the stored procedure here
    @NameOfClub nvarchar(200)
AS
BEGIN
    TRUNCATE TABLE SSIS.ClubNameTable;
    if(@NameOfClub = 'Eagle Plate' or @NameOfClub = 'Atlanta United FC')
    begin
    insert into ssis.ClubNameTable ([NameOfClub], [FirstName], [LastName])
        SELECT
            p.FirstName,
            COUNT(p.LastName) as 'Number of Last Names',                
            NameOfClub
    FROM [Location].Club as C
            JOIN [Location].ClubDetails as CD on c.ClubID = cd.ClubID
            JOIN [Player].Player as P on CD.PlayerID = P.PlayerID
            Where C.NameOfClub = @NameOfClub
            GROUP BY c.NameOfClub, p.FirstName, p.LastName
            ORDER BY p.LastName ASC
        declare 
        @RowCount int
            SET @RowCount = (SELECT COUNT(*) FROM Location.Club)
    end

    else
    begin
    select 'Please choose either Eagle Plate or Atlanta United FC'
    end
END
GO

Upvotes: 3

Related Questions