title: Set variable to SCOPE_IDENTITY inside of IF statement
body: <p>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 <code>SCOPE_IDENTITY</code> 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 <code>SCOPE_IDENTITY</code> from within an <code>IF...ELSE</code> statement.</p>
  
  <p>My two tables:</p>
  
  <pre><code>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
  )
  </code></pre>
  
  <p>Stored Procedure:</p>
  
  <pre><code>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
  </code></pre>
  
  <p>This returns <code>Incorrect syntax near the keyword 'ELSE'</code></p>
  
  <p>What would be the best method for accomplishing this lookup/insert? After I get the ID I will then do the following</p>
  
  <pre><code>INSERT INTO ActionTable(ObjectID, ActionName) VALUES(@ObjectID, @ActionName)
  
  SELECT SCOPE_IDENTITY()
  </code></pre>