将 exec sp_executesql 结果加载到表中

时间:2023-02-07
本文介绍了将 exec sp_executesql 结果加载到表中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

我从我的上一个问题中有以下查询,它在动态表中的 SQL.我怎样才能把它传到一张桌子上?我的意思是像 select * from sp_executesql @query.

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.

我尝试了 openrowset,但我的安全权限不允许.还有其他帮助吗?

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

谢谢,

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) 将显示列名

Print (@query) will display the column names

选择[GRADE-BASIS-INDICATOR],[MOST-CURRENT-CODE],[PAY-PERIOD-NUMBER],[DATE-PROC-PP-BEGINS-CN],[DATE-PROC-PP-BEGINS-YR],[行动-代码],[无人员-现金-奖]......一共1085个

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

推荐答案

由于拉取动态字段列表,这需要作为一个SELECT {fields} INTO ##tmp FROM...code> 因为没有简单的方法来获得 CREATE TABLE 语句,特别是如果 bear_crossjoin 表中没有列出的数据类型.因此,更新动态 SQL 以增加一行,如下所示:

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;

全局临时表(即 ##name 而不是 #name)将在子进程中创建后继续存在.一张真正的桌子也能幸存下来.但是一旦子进程(即动态 SQL)结束,本地临时表(即 #name 而不是 ##name)就会消失.

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.

这篇关于将 exec sp_executesql 结果加载到表中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

上一篇:捕获字段状态更改的开始和结束时间 下一篇:将参数从 C# 流式传输到 T-SQL SP?

相关文章

最新文章