我从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);
答案 0 :(得分: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
答案 1 :(得分: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
。
答案 2 :(得分: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);