我基本上想要插入一些内容并使用OUTPUT函数从插入的行中获取一些值。这很简单。 但是,即使没有插入任何内容,我也希望我的查询获取这些值,因为主要内容已经存在。
DECLARE @existingId bigint;
IF EXISTS(SELECT @existingId = Id FROM MyTable WHERE Name = @Name)
OUTPUT @existingId;
RETURN;
INSERT INTO MyTable (Name) OUTPUT INSERTED.Id VALUES (@Name);
这总是给我Incorrect syntax near '='.
任何想法如何实现这种行为?
答案 0 :(得分:0)
我相信你错过了一个开合括号,试试:
DECLARE @existingId bigint;
IF EXISTS(SELECT @existingId =( Id FROM MyTable WHERE Name = @Name))
OUTPUT @existingId;
RETURN;
INSERT INTO MyTable (Name) OUTPUT INSERTED.Id VALUES (@Name);
答案 1 :(得分:0)
output
需要一张桌子,而不是一张值。所以你努力编写的代码应该更像这样:
DECLARE @out table (existingid bigint);
INSERT INTO @out(existingid)
SELECT Id FROM MyTable WHERE Name = @Name;
IF EXISTS (SELECT * FROM @out)
RETURN;
INSERT INTO MyTable (Name)
OUTPUT INSERTED.Id INTO @out
VALUES (@Name);
但是,此代码具有竞争条件。因为有人可以在存在的检查和Name
之间插入insert
。要真正解决此问题,您应该使用try
/ catch
并在name
上拥有唯一索引。以下是代码示例:
DECLARE @out table (existingid bigint);
BEGIN TRY
INSERT INTO MyTable (Name)
OUTPUT INSERTED.Id INTO @out
VALUES (@Name);
RETURN
END TRY
BEGIN CATCH -- assume there is a duplicate although there could be other problems
INSERT INTO @out(existingid)
SELECT Id FROM MyTable WHERE Name = @Name;
END CATCH;
以下代码创建唯一索引:
create unique index idx_mytable_name on mytable(name);