我正在尝试编写一个存储过程来检查是否存在记录,如果它不存在,请执行一个返回SCOPE_IDENTITY
的插入,如果确实存在则只返回该对象的ID。在我在程序中获得此信息后,我需要使用它进行进一步处理,并且不确定如何从SCOPE_IDENTITY
语句中获取IF...ELSE
。
我的两张桌子:
CREATE TABLE [dbo].[ActionTable] (
[ActionID] [int] IDENTITY(1, 1) NOT NULL,
[ObjectID] [int] NOT NULL,
[ActionName] [nvarchar](255) NOT NULL
)
CREATE TABLE [dbo].[ObjectTable] (
[ObjectID] [int] IDENTITY(1, 1) NOT NULL,
[ObjectName] [nvarchar](255) NOT NULL
)
存储过程:
CREATE PROCEDURE [dbo].[SetAction]
@ActionName [nvarchar](255),
@ObjectName [nvarchar](255)
AS
DECLARE @ObjectID [int]
--I have tried the following
IF NOT EXISTS(SELECT ObjectID FROM ObjectTable WHERE ObjectName = @ObjectName)
INSERT INTO ObjectTable(ObjectName)VALUES(@ObjectName)
--Here I need to set @ObjectID = SELECT SCOPE_IDENTITY()
ELSE
SELECT @ObjectID = ObjectID FROM ObjectTable WHERE ObjectName = @ObjectName
这会返回Incorrect syntax near the keyword 'ELSE'
完成此查找/插入的最佳方法是什么?获得ID后,我将执行以下操作
INSERT INTO ActionTable(ObjectID, ActionName) VALUES(@ObjectID, @ActionName)
SELECT SCOPE_IDENTITY()
答案 0 :(得分:26)
如果你有多件事要做,你需要一个BEGIN END
IF NOT EXISTS(SELECT ObjectID FROM ObjectTable WHERE ObjectName = @ObjectName)
BEGIN
INSERT INTO ObjectTable(ObjectName)VALUES(@ObjectName)
SET @ObjectID = SCOPE_IDENTITY()
END
ELSE
BEGIN
SELECT @ObjectID = ObjectID FROM ObjectTable WHERE ObjectName = @ObjectName
END
答案 1 :(得分:4)
您应该始终使用BEGIN / END,即使只有一个语句,以便稍后添加语句时代码不会中断。
IF ...
BEGIN
... statements
END
ELSE
BEGIN
... statements
END