1

我正在从 PowerShell 向 SQL Server 2005 中插入行。我需要在我的代码中添加 WHERE NOT EXISTS 子句以停止插入重复项。我正在测试 SSMS 中的 SQL 代码,但无法使其正常工作。

以下代码中的错误在哪里?

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);
4

3 回答 3

1

您的语法无效 - 您不能将WHERE子句应用于VALUES. 试试这个:

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
于 2010-06-28T09:01:59.933 回答
1

您不能为此INSERT....VALUES添加一个WHERE子句。如果您这样做INSERT...VALUES,这些值将被插入 - 句点。

您需要改变检查方式:

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)

做一个IF NOT EXISTS检查,如果成功,那么你INSERT....VALUES

于 2010-06-28T09:02:13.177 回答
1

你也可以做

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);
于 2010-06-28T09:04:52.397 回答