我正在嘗試編寫一個存儲過程來檢查記錄是否存在,如果它不存在,請執行一個返回SCOPE_IDENTITY
的插入,如果存在,只需返回ID物體。在程序中得到這些信息後,我需要對其進行進一步處理,並且不確定如何完成從IF...ELSE
聲明中獲得SCOPE_IDENTITY
。將變量設置爲IF語句中的SCOPE_IDENTITY
我的兩個表:
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()