Loading exec sp_executesql results into a table

2019-09-02 05:08发布

问题:

I have the below query from my previous question and this executes in SQL in a dynamic table. How can i pass this into a table? I mean something like select * from sp_executesql @query.

I tried openrowset but my security privilages do not allow it. Any other help?

Thanks,

Declare @cols as NVARCHAR(MAX), @query as NVARCHAR(MAX)

select @cols = STUFF((SELECT ',' + QUOTENAME(FIELD_NAME) 
                from bear_crossjoin
                group by Field_Name, FIELDNUMBER
                order by FIELDNUMBER
        FOR XML PATH(''), TYPE
        ).value('.', 'NVARCHAR(MAX)') 
    ,1,1,'')

set @query = N'SELECT ' + @cols + N' 
            from 
            (
                select substring, Field_Name,
                  rn = row_number() over(partition by field_name order by fieldnumber)
                from bear_crossjoin
            ) x
            pivot 
            (
                max(substring)
                for Field_Name in (' + @cols + N')
            ) p ' 
exec sp_executesql @query

Print (@query) will display the column names

SELECT [GRADE-BASIS-INDICATOR],[MOST-CURRENT-CODE],[PAY-PERIOD-NUMBER],[DATE-PROC-PP-BEGINS-CN],[DATE-PROC-PP-BEGINS-YR],[ACTION-CODE],[NO-PERSONS-CASH-AWARD]......there are 1085 of them

回答1:

Due to pulling a dynamic field list, this kinda needs to be done as a SELECT {fields} INTO ##tmp FROM... since there is no easy way to get a CREATE TABLE statement, especially if the bear_crossjoin table does not have the datatypes listed in it. So, update the Dynamic SQL to have one extra line as follows:

set @query = N'SELECT ' + @cols + N' 
               INTO ##TempResults  -- add this one line!!
            from 
            (
...
exec sp_executesql @query

SELECT * FROM ##TempResults;

A Global Temp Table (i.e. ##name instead of #name) will survive being created in a sub-process. A real table would also survive. But a local temp table (i.e. #name instead of ##name) will disappear once the subprocess (i.e. the Dynamic SQL) ends.