|
|
Question : SQL Stored Procedure - Insert and Get ID if not found, Get ID if found
|
|
I have a VB.NET 2005 app and SQL Server 2005 DB. The program adds song information to the database. The information the user inputs is: Artist, Song Title, Track Number, and CD Title. The database is already built and has over 1,000 songs in it already that I have imported from an XML file. But now, I'm building a VB.NET app that has an input screen to enter in one song at a time. What I want is a stored procedure that does the following:
I have an ARTISTS table. The table consists of two fields: ID (int) autonumber and ARTIST (nvarchar(100)). I want a stored procedure that selects the ID when I insert an artist. However, if the artist already exists, I want the ID number associated with it. If the artist does not already exist in the table, I want it to be added, and to select the newly created ID. What would the SQL statement for this stored procedure be? I want it to be called "InsertArtist". Please help! :)
|
Answer : SQL Stored Procedure - Insert and Get ID if not found, Get ID if found
|
|
I know you requested the SP to "select" the new artistID, but it's more convenient on the VB side if you return the ArtistId in an output parameter. I've adapted Aneesh's answer here to show you how. Then on the VB side, you can pick up the result in an output parameter.
CREATE PROCEDURE InsertArtist @Artist NVARCHAR(100), @ArtistID Int OUTPUT --match the datatype of the identity column here AS SET NOCOUNT ON IF EXISTS (SELECT 1 FROM Artists WHERE Artist = @Artist) BEGIN SELECT @ArtistID=ArtistID FROM Artists WHERE Artist = @Artist RETURN 0 END INSERT INTO Artists SELECT @Artist SELECT @ArtistID=SCOPE_IDENTITY() RETURN 0
|
|
|
|
|