Skip to content
Advertisement

How to use a table variable within EXECUTE command?

I have this code:

DECLARE @mytable TABLE (x INT);
EXECUTE ('SELECT * FROM ' + @mytable);

When I run the code, I get this error:

Must declare the scalar variable “@mytable “.

I know that @mytable variable is of type TABLE and it should be VARCHAR, but how to play around it?

Advertisement

Answer

Simply, you can’t.

This is not possible, cause the table variable is isolated from the scope of the Dynamic SQL. You can only use temporary and normal tables.

Or declare it withing the Dynamic SQL as

EXECUTE sp_executesql N'DECLARE @MyTABLE TABLE (x int); 
                        INSERT INTO @MyTable VALUES (1);
                        SELECT * FROM @MyTable';
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement