Monday, March 26, 2012

Insert without duplicates

i have a table that contains a list of musical artist and an index. I want to insert artists into that table however, i dont want to insert any name that already exists. How do i do that?

Here is my statement:
INSERT INTO [Artists Table] (ArtistName) VALUES (@.ArtistName)

Create EITHER a Primary Key or a Unique Index on ArtistName

|||

In addition to the primary key or unique constraint if you alter your insert to the following, you will avoid getting PRIMARY KEY VIOLATION errors:

if not exists
( select 0 from [Artists Table] where artistName = @.artistName )
INSERT INTO [Artists Table] (ArtistName) VALUES (@.ArtistName)


Dave

|||

Hi,

or if you want to do this within one step rather than a batch

INSERT INTO [Artists Table] (ArtistName)
SELECT @.ArtistName
WHERE NOT EXISTS
(
select * from [Artists Table] where artistName = @.artistName
)

HTH, Jens K. Suessmeyer.


http://www.sqlserver2005.de

|||Thanks!. Thats works for 1 variable, however how do i do it for multiple.... For example:

INSERT INTO [Recordings] (RecordingTitle, ArtistName = @.ArtistName)
SELECT @.RecordingTitle
WHERE NOT EXISTS
(
select * from [Recordings] where RecordingTitle = @.RecordingTitle
)

I want to pass in the ArtistName, but not have it verify that because it is a foreign key.
|||I think i figured it out:

INSERT INTO Recordings
(RecordingTitle, ArtistName)
SELECT @.RecordingTitle AS Expr1, @.ArtistName AS Expr2
WHERE (NOT EXISTS
(SELECT RecordingID, RecordingTitle, ArtistName
FROM Recordings AS Recordings_1
WHERE (RecordingTitle = @.RecordingTitle))) AND (@.ArtistName = @.ArtistName)|||Good, I have same question, actually Jens K. Suessmeyer help me figure this out yesterday. Thanks Jens.

No comments:

Post a Comment