Skip to content
Advertisement

Creating and Selecting table variables dynamically in SQL Server stored procedure?

Please guide me how to create table variables dynamically. I know it can be like this:

How I will create if dont know columns and data types. Scenario is I have to create table variable as per a physical tables and selct data into them, use them in SP and then return data in table variables to C# program.

For example I have a table Employees. I want create a table variable with same structure as Employyes have. But mentioning columns take a lot time (as Employees have about 100 columns)

Please advice.

Advertisement

Answer

So here is how you can build the DECLARE TABLE statement dynamically:

But now what? You can’t insert into it from outside the scope of dynamic SQL:

Yields this error:

Once again, a scoping issue – @people only exists in the dynamic SQL and ceases to exist as soon as it’s finished. So while you could proceed and append to the @sql variable:

…this will get out of hand very quickly. And I still have no idea how your C# code can be aware of all the columns and data types involved, but it’s too hard to write the SQL to do so… you know you can drag the columns node from Object Explorer onto a query window and it will produce a nice comma-separated list of column names for you, right?

User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement