TSQL select into Temp table from dynamic sql

前端 未结 5 1220
星月不相逢
星月不相逢 2020-12-03 13:35

This seems relatively simple, but apparently it\'s not.

I need to create a temp table based on an existing table via the select into syntax:

SELECT *         


        
5条回答
  •  误落风尘
    2020-12-03 14:29

    How I did it with a pivot in dynamic sql (#AccPurch was created prior to this)

    DECLARE @sql AS nvarchar(MAX)
    declare @Month Nvarchar(1000)
    
    --DROP TABLE #temp
    select distinct YYYYMM into #temp from #AccPurch AS ap
    SELECT  @Month = COALESCE(@Month, '') + '[' + CAST(YYYYMM AS VarChar(8)) + '],' FROM    #temp
    
    SELECT   @Month= LEFT(@Month,len(@Month)-1)
    
    
    SET @sql = N'SELECT UserID, '+ @Month + N' into ##final_Donovan_12345 FROM (
    Select ap.AccPurch ,
           ap.YYYYMM ,
           ap.UserID ,
           ap.AccountNumber
    FROM #AccPurch AS ap 
    ) p
    Pivot (SUM(AccPurch) FOR YYYYMM IN ('+@Month+ N')) as pvt'
    
    
    EXEC sp_executesql @sql
    
    Select * INTO #final From ##final_Donovan_12345
    
    DROP TABLE  ##final_Donovan_12345
    
    Select * From #final AS f
    

提交回复
热议问题