I am trying to write a stored procedure that will check for the existence of a record and if it does not exist do an insert returning the SCOPE_IDENTITY
and if it does exist simply return the ID of the object. After I get this information in the procedure I need to do further processing with it and am unsure of how to accomplish getting the SCOPE_IDENTITY
from within an IF...ELSE
statement.
My two tables:
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
)
Stored Procedure:
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
This returns Incorrect syntax near the keyword 'ELSE'
What would be the best method for accomplishing this lookup/insert? After I get the ID I will then do the following
INSERT INTO ActionTable(ObjectID, ActionName) VALUES(@ObjectID, @ActionName)
SELECT SCOPE_IDENTITY()