如果sql server中不存在该行,是否可以使用"if not exists"来插入行?

3 sql sql-server

insert into Attributes (Id, Disabled, AttributeValue) 
values (@id, @disabled, @attr_value)
if not exists
(
select * from Attributes
where 
Id = @id
)
Run Code Online (Sandbox Code Playgroud)
  • 不确定,如果这是一个有效的查询.
  • 我见过人们使用不存在的地方.有什么区别以及如何使用不存在的地方?当我放在不存在的地方时,它会说"语法附近的语法不正确".

我也检查了这些问题.但是,如果不存在,它似乎没有插入使用的查询. 只有插入行,如果它不是已经存在SQL条件插入如果行不存在

  • 我错过了什么吗?我应该只在不存在的地方使用吗?

Tar*_*ryn 10

将其更改为 INSERT INTO SELECT

INSERT INTO Attributes (Id, Disabled, AttributeValue) 
SELECT @id, @disabled, @attr_value
WHERE NOT EXISTS
(
    select * from Attributes
    where 
    Id = @id
)
Run Code Online (Sandbox Code Playgroud)


Ash*_*nko 3

你需要执行这样的事情

IF NOT EXISTS (select 1 from Attributes where Id = @id)
BEGIN
    insert into Attributes (Id, Disabled, AttributeValue) 
    values (@id, @disabled, @attr_value)
END
Run Code Online (Sandbox Code Playgroud)

这通常是通过 else 子句来更新行(如果存在)来完成的。