views:

29

answers:

3

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);
+1  A: 

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
AdaTheDev
darn - beat me by 13 seconds.... but that BEGIN...END pair really isn't needed... (just to be nit-picky <grin>)
marc_s
Thank you very much, couldn't understand why the select.. where not exists worked and the insert into... didn't
Andrew
+1  A: 

You cannot do an INSERT....VALUES and add a WHERE clause to that. If you do INSERT...VALUES, those values get inserted - period.

You need to change around the way you do your check:

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)
     INSERT INTO dbo.PrptyValSrce
        (PrptySrceName, PrptyNameSrce, PrptyValSrce, PrptyTS) 
     VALUES
        (@property, @propertyDesc, @value, @Timestamp)

Do a IF NOT EXISTS check, and if that succeeds, then do you INSERT....VALUES.

marc_s
+1  A: 

You could also do

INSERT INTO dbo.PrptyValSrce
    (PrptySrceName, PrptyNameSrce, PrptyValSrce, PrptyTS) 
SELECT @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);
Martin Smith