Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create temp table with dynamic SQL query result

I have this stored procedure:

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)

and it's generating this result:

result

I want to create temp table or variable type table for following result , remember the column of this result are dynamically rendered. Sometimes result returns more columns and sometimes with less but first 3 columns remain the same for every result. So kindly help for creating dynamic table inside the stored procedure.

like image 954
Fraz Zaki Avatar asked Oct 24 '25 14:10

Fraz Zaki


1 Answers

You can do:

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

Since you execute this dynamically, you cannot use #TEMPTABLE because a local temp table will only exist in the scope of the query that defines it. Using ## creates a global temp table which will be accessible outside the scope of the dynamic query.

like image 57
HoneyBadger Avatar answered Oct 27 '25 03:10

HoneyBadger



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!