2

I am facing some issues in saving the execution of stored procedure / scalar function into a table variable.

The function / stored procedure returns dynamic columns and I need to create a dynamic table to save the result of that function into it so that I can use the table.

Example: the stored procedure spGetEmployeeInfo could return employee name, employee id, etc. on such criteria they return only employee name,.

Is there a way to create a dynamic table and save the result into it after execute the stored procedure, or any suggestion.

Thanks

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Sami
  • 21
  • 1
  • *"is there a way to create a dynamic table"* Use a `SELECT...INTO`? You'll need to do it *inside* the dynamic statement though, not outside of it. – Thom A Feb 17 '21 at 17:07

1 Answers1

1

I don't like to get into this situation too often, but when I do, what I do is have the stored proc output into a global temp table. The name of the table is passed in as a parameter by the user. For instance:

create procedure dynamicBeCareful 
    @toggle bit, 
    @globalTempTableName varchar(50) 
as 

-- initializations

    if left(@globalTempTableName,2) <> '##'
      throw 50000, '@globalTempTableName must start with ##', 1;

    declare @sql varchar(max);

-- build dynamic sql

    if @toggle = 1 
        set @sql = 'select * into @tempTable from table1';
    else 
        set @sql = 'select * into @tempTable from table2';

    set @sql = replace(@sql, '@tempTable', @globalTempTableName);

-- terminations

    exec (@sql); 

    declare @msg = 'Your results are in ' + @globalTempTableName;
    print (@msg);

Then use it like this:

exec dynamicBeCareful 1, '##temp';

select * from ##temp;

Beyond just being dynamic in output, it also can get you out of nested insert-exec limitations.

pwilcox
  • 5,542
  • 1
  • 19
  • 31