Damien Damien - 22 days ago 9
SQL Question

SQL Server : INSERT with a condition

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. Thank you

Answer

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