Damien Damien - 17 days ago 6
SQL Question

MSSQL INSERT with a condition

I want to insert into my "Files-Favorites" table only if the values i'm trying to pass aren'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
Comments