1

I want to insert into my Files-Favorites table only if the values I'm trying to pass isn't in there already.

I tried:

INSERT INTO [Files-Favorites](fileID,auditorID)  
     VALUES ('1', '34') 
      WHERE (fileID != '1' 
        AND auditorID != '34')

This doesn't work. I'm trying not to INSERT duplicate values. How do I pull this off? This is for a Microsoft SQL Server 2005.

3 Answers 3

6

Try using if not exists

IF NOT EXISTS(SELECT * FROM [Files-Favorites] WHERE fileID = '1' AND auditorID = '34') 
BEGIN 
    INSERT INTO [Files-Favorites](fileID, auditorID) 
    VALUES('1', '34') 
END
Sign up to request clarification or add additional context in comments.

1 Comment

this is not TRANSACTION safe
2

I would use a composite (multi-column) key rather than checking on each insert

ALTER TABLE [Files-Favorites] ADD CONSTRAINT unique_1 UNIQUE(fileID,auditorID)

2 Comments

this is way beyond me, not sure what you mean here
you can add unique constraint to prevent duplicate data. It is not good practice to check on each insert.
1

We can use EXISTS with sub query to check the data existence and insert accordingly:

INSERT INTO [Files-Favorites](fileID,auditorID) 
SELECT fileID, auditorID FROM (
SELECT '1' fileID,'34' auditorID) t
WHERE NOT EXISTS(SELECT tm.fileID FROM [Files-Favorites] tm 
                 WHERE tm.fileID = t.fileID AND tm.auditorID = t.auditorID)

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.