pivot动态查询并将结果存储到表中

时间:2015-02-26 18:26:45

标签: sql-server-2008 dynamic pivot

我有一个动态查询,其中列数有所不同。我想将结果存储到表中以便进一步处理。

我添加了一个insert into子句来将结果存储到表中,但是我收到了语法错误。

Msg 102, Level 15, State 1, Line 14 Incorrect syntax near ')'

我正在使用MS SQL server management studio 2008 R2。

这是我的疑问:

 IF OBJECT_ID('TEMPDB..#datesTemp') IS NOT NULL BEGIN   DROP TABLE #datesTemp END 
 DECLARE @cols AS NVARCHAR(MAX),
    @colNames AS NVARCHAR(MAX),
    @query AS NVARCHAR(MAX),
    @startDate datetime

SET @startDate = '2005-01-01'

;with dates as
(
  select @startdate datelist, 1 sp
  union all
  select dateadd(month, 1, datelist), sp+1
  from dates
  where sp+1 <= 122 -- change this number 5 to the number of months you need
)
select   sp,
  CONVERT(VARCHAR(7), datelist, 120) as MONTHANDYEAR 
into #datesTemp
from dates 
option (maxrecursion 122)

select @cols = STUFF((SELECT ',' + QUOTENAME(monthandyear) 
                    from #datesTemp
                    group by monthandyear, sp
                    order by sp
            FOR XML PATH(''), TYPE
            ).value('.', 'NVARCHAR(MAX)') 
        ,1,1,'')

select @colNames = STUFF((SELECT  ', isnull(' + QUOTENAME(monthandyear)+', 0) as '+QUOTENAME(monthandyear)
                    from #datesTemp
                    group by monthandyear, sp
                    order by sp
            FOR XML PATH(''), TYPE
            ).value('.', 'NVARCHAR(MAX)') 
,1,1,'')


set @query = 'select * into recmonth_temp from 
            (SELECT FIPS, DATA_TYPE,' + @colNames + ' 
             from 
             (
                select FIPS, DATA_TYPE,REC_MONTH, TOTAL_RECORDS 
                from REPORTING.DBO.APEX_CUMULATIVE_SUMMARY_ALL_STAGING_NEW A join member1.dbo.fipscode F
                on a.fips = f.fipscode

            ) x
            pivot 
            (
                sum(TOTAL_RECORDS)
                for REC_MONTH in (' + @cols + ')
            ) p) '

execute(@query)

0 个答案:

没有答案