Question

This is a generic question with a specific example.

I have a table with three fields (genreID (PK IDENTITY), genre, and subGenre). The table has a unique constraint on (genre, subGenre) combination.

I am wondering how I could go about modifying the stored procedure to insert if it DOES NOT exist in the table, otherwise return the genreID of the existing genre if it DOES exist.

CREATE PROCEDURE spInsertGenre
    @genreID int OUTPUT,
    @genre varchar(100),
    @subGenre varchar(100)= NULL
AS
BEGIN
    INSERT INTO Genre
    (
        genre,
        subGenre
    )
    Values (
        @genre,
        @subGenre
    )

    SELECT @genreID = SCOPE_IDENTITY()
END
GO
Was it helpful?

Solution

You can try to select the row that would be inserted by your SP before you do the insert:

CREATE PROCEDURE spInsertGenre
    @genreID int OUTPUT,
    @genre varchar(100),
    @subGenre varchar(100)= NULL
AS
BEGIN
    -- if the row to be inserted already exists, put the genreID into the @genreID output parameter 
    SELECT @genreID = genreID
    FROM Genre 
    WHERE genre = @genre 
    AND subGenre = @subGenre

    IF @genreID IS NULL -- if the genreID was not found, do an insert and select the new genreID to the @genreID output parameter
    BEGIN
        INSERT INTO Genre
        (
            genre,
            subGenre
        )
        Values (
            @genre,
            @subGenre
        )

        SELECT @genreID = SCOPE_IDENTITY()
    END
END
GO
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top