I am inserting rows into SQL Server 2005 from PowerShell. I need to add a WHERE NOT EXISTS clause to my code to stop inserting duplicates. I am testing the SQL code in SSMS and cannot get it to work.
Where is the mistake in the following code?
INSERT INTO dbo.PrptyValSrce
(PrptySrceName, PrptyNameSrce, PrptyValSrce, PrptyTS)
VALUES
(@property, @propertyDesc, @value, @Timestamp)
WHERE NOT EXISTS
(SELECT * from PrptyValSrce as b
WHERE b.Seqno
AND b.PrptySrceName = @property
AND b.PrptyNameSrce = @propertyDesc
AND b.PrptyValSrce = @value
AND b.PrptyTS = @Timestamp);
Your syntax is invalid - you can't have a WHERE
clause applied to VALUES
. Try this:
IF NOT EXISTS(
SELECT *
from PrptyValSrce as b
WHERE b.Seqno
AND b.PrptySrceName = @property
AND b.PrptyNameSrce = @propertyDesc
AND b.PrptyValSrce = @value
AND b.PrptyTS = @Timestamp)
BEGIN
INSERT INTO dbo.PrptyValSrce
(PrptySrceName, PrptyNameSrce, PrptyValSrce, PrptyTS)
VALUES
(@property, @propertyDesc, @value, @Timestamp)
END