2

I am just wondering if it is possible to use a variable within a stored procedure. For Example:

    CASE    @productType
    WHEN 1 THEN
    DECLARE @table = ‘products1’
    WHEN 2 THEN
    DECLARE @table = ‘products2’
END

SELECT * FROM @table;

Obviously this does not work, just wondering if there is a way to accomplish this.

2 Answers 2

6

Yes, there is a way. You can use dynamic sql.

DECLARE @productType INT = 1
DECLARE @table  NVARCHAR(MAX)
DECLARE @sql    NVARCHAR(MAX)

SELECT @table = 
    CASE @productType
        WHEN 1 THEN 'products1'
        WHEN 2 THEN 'products2'
    END

SELECT @sql = 'SELECT * FROM ' + QUOTENAME(@table);

EXEC(@sql)
Sign up to request clarification or add additional context in comments.

Comments

2

You can simply use a if else if statement :

DECLARE @productType INT = 2
IF @productType = 1
    SELECT * FROM products1
ELSE IF @productType = 2
    SELECT * FROM products2

Or Using sp_executesql:

DECLARE @productType INT = 1;
DECLARE @table  NVARCHAR(MAX);
DECLARE @sql    NVARCHAR(MAX);


SELECT @table = 
    CASE @productType
        WHEN 1 THEN 'products1'
        WHEN 2 THEN 'products2'
    END;

SELECT @sql = 'SELECT * FROM ' + QUOTENAME(@table);

EXEC sp_executesql @sql;

4 Comments

Yes, This was a simple example but I am wanting to use this on much more complex procedures where using this method would be unwieldily
Can you provide an explantion of your scenario, much of the time it's better to avoid dynamic SQL
I see, Is this for performance reasons? the scenario is basically because I have a very long statement where the table name must be changed throughout. there are many scenarios so i would have to have 20+ if statements and copy paste a lot of code
No this is for security reasons, in your case you should use EXEC sp_executesql @sql rather than EXEC (@sql). stackoverflow.com/questions/548090/…

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.