9

I'm looking for a more efficient way of completing this task. I need to set a variable equal to an ID if it exists, and if not insert it and then set the variable to the inserted identity. I can accomplish this by doing the following:

@VariableName --sent through to stored procedure

DECLARE @VariableID [int]

IF EXISTS(SELECT VariableID FROM VariableTable WHERE VariableName = @VariableName)
    SET @VariableID = (SELECT VariableID FROM VariableTable WHERE VariableName = @VariableName)
ELSE 
    INSERT INTO VariableTable(VariableName) VALUES(@VariableName)
    SET @VariableID = SCOPE_IDENTITY();
END

However it seems inefficient to run the same query twice (check if exists and if it does set the variable)

Just looking for suggestions on a better way to accomplish this task.

5 Answers 5

16

Try :

DECLARE @VariableID [int]
SELECT @VariableID=VariableID FROM VariableTable WHERE VariableName = @VariableName

IF @VariableID IS NULL
BEGIN
    INSERT INTO VariableTable(VariableName) VALUES(@VariableName)
    SET @VariableID = SCOPE_IDENTITY();
END
Sign up to request clarification or add additional context in comments.

Comments

1

I tested this snippet and it executes correctly:

DECLARE @VariableID [int]
SET @VariableID=(SELECT VariableID FROM VariableTable WHERE VariableName = @VariableName)
IF @VariableID IS NULL
BEGIN
  INSERT INTO VariableTable(VariableName) VALUES(@VariableName)
  SET @VariableID = SCOPE_IDENTITY();
END

Comments

1

Here a lite modification to @Mithrandir answer. You can use TOP 1 that help you to speed up the result when you are not comparing against unique field. e.g.

DECLARE @EXISTS AS BIT
SET @EXISTS = 0
SELECT TOP 1 @EXISTS = 1 FROM MyTable WHERE MyYear = @Year

Comments

1

Try this:

INSERT INTO VariableTable (VariableID )
 SELECT SCOPE_IDENTITY()
FROM VariableTable
WHERE not exists
(
 SELECT VariableID FROM VariableTable WHERE VariableName = @VariableName
)

Then if you need the id you would have to set the variable the @@IDentity. I think this is most efficient as you aren't making a third query, but just just getting the last ID inserted.

Comments

0

Try this amusing exception. Remember there's no BEGIN and END, so the next statement after the IF should be conditional. Now ask yourself why the first variable exists:

declare @check binary
declare @predeclared varchar(100)
select @check = 0

if @check = 1
   declare @conditionaldeclare nvarchar(4000)
   select @conditionaldeclare = 'conditionaldeclare'
   print @conditionaldeclare


if @check = 1
   select @predeclared = 'predeclared'
   print @predeclared

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.