gpt4 book ai didi

sql - 如何使用动态 SQL 查询结果创建临时表

转载 作者:行者123 更新时间:2023-12-04 02:00:55 25 4
gpt4 key购买 nike

我有这个存储过程:

Declare @MarketID AS NVARCHAR(MAX) = '1.136529848';
Declare @UserID AS NVARCHAR(MAX) = '6a309d84-d1c6-434d-b9df-4f96a74da912';

DECLARE @colsSelect AS NVARCHAR(MAX);
DECLARE @colsTemp AS NVARCHAR(MAX);
DECLARE @query AS NVARCHAR(MAX);

SELECT
@colsSelect = STUFF((SELECT distinct ',' +
'''''' + ' as ' + QUOTENAME(name)
FROM RunnersInfoes AS t
WHERE marketID = @MarketID
FOR XML PATH(''), TYPE).value('.', 'NVARCHAR(MAX)') , 1, 1, '');

PRINT @colsSelect

SET @query= ';WITH cte AS
(
SELECT
id, ParentId, 0 AS Level, Share, AccountTypeName, FirstName
FROM
dbo.View_UserProfile
WHERE
View_UserProfile.id = ' + '''' + @UserID + '''' +'
UNION ALL
SELECT
t.id, t.ParentId, Level + 1 AS Level, t.Share, t.AccountTypeName, t.FirstName
FROM
View_UserProfile t
INNER JOIN
cte ON t.ParentId = cte.id
)
SELECT
ID, AccountTypeName AS Type, FirstName AS Name, ' + @colsSelect + '
FROM cte AS t'

EXECUTE (@query)

它产生了这个结果:

result

我想为以下结果创建临时表或变量类型表,请记住此结果的列是动态呈现的。有时结果返回更多列,有时返回更少但前 3 列对于每个结果都保持不变。所以请帮助在存储过程中创建动态表。

最佳答案

你可以做:

SELECT ID
, AccountTypeName AS Type
, FirstName AS Name
, ' + @colsSelect + '
INTO ##TEMPTABLE
FROM cte AS t

由于您动态执行此操作,因此不能使用 #TEMPTABLE因为本地临时表只会存在于定义它的查询范围内。使用 ##创建一个全局临时表,该表可在动态查询范围之外访问。

关于sql - 如何使用动态 SQL 查询结果创建临时表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47329118/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com