Loading exec sp_executesql results into a table(将 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 结果加载到表中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:将 exec sp_executesql 结果加载到表中
基础教程推荐
- 无法在 ubuntu 中启动 mysql 服务器 2021-01-01
- SQL Server 中单行 MERGE/upsert 的语法 2021-01-01
- 将数据从 MS SQL 迁移到 PostgreSQL? 2022-01-01
- 在 VB.NET 中更新 SQL Server DateTime 列 2021-01-01
- SQL Server 2016更改对象所有者 2022-01-01
- 如何在 SQL Server 的嵌套过程中处理事务? 2021-01-01
- 使用pyodbc“不安全"的Python多处理和数据库访问? 2022-01-01
- Sql Server 字符串到日期的转换 2021-01-01
- SQL Server:只有 GROUP BY 中的最后一个条目 2021-01-01
- ERROR 2006 (HY000): MySQL 服务器已经消失 2021-01-01