insert into Attributes (Id, Disabled, AttributeValue)
values (@id, @disabled, @attr_value)
if not exists
(
select * from Attributes
where
Id = @id
)
我也检查了这些问题。但是,它似乎没有使用插入的查询,如果不存在。 Only inserting a row if it's not already there和 sql conditional insert if row doesn't already exist
答案 0 :(得分:8)
将其更改为INSERT INTO SELECT
INSERT INTO Attributes (Id, Disabled, AttributeValue)
SELECT @id, @disabled, @attr_value
WHERE NOT EXISTS
(
select * from Attributes
where
Id = @id
)
答案 1 :(得分:2)
你需要执行类似这样的事情
IF NOT EXISTS (select 1 from Attributes where Id = @id)
BEGIN
insert into Attributes (Id, Disabled, AttributeValue)
values (@id, @disabled, @attr_value)
END
这通常使用else子句来更新行(如果存在)。
答案 2 :(得分:2)
考虑使用MERGE
:
MERGE INTO Attributes
USING ( values (@id, @disabled, @attr_value ) )
AS source ( Id, Disabled, AttributeValue )
ON source.Id = Attributes.Id
WHEN NOT MATCHED THEN
INSERT ( Id, Disabled, AttributeValue )
VALUES ( Id, Disabled, AttributeValue );
一个优点是您还可以在Id
存在时更新值,例如
MERGE INTO Attributes
USING ( values (@id, @disabled, @attr_value ) )
AS source ( Id, Disabled, AttributeValue )
ON source.Id = Attributes.Id
WHEN MATCHED THEN
UPDATE
SET Id = source.Id,
Disabled = source.Disabled,
AttributeValue = source.AttributeValue
WHEN NOT MATCHED THEN
INSERT ( Id, Disabled, AttributeValue )
VALUES ( Id, Disabled, AttributeValue );