I have a dynamic crosstab which I need to build every month. I thought I could use a view to do this, and have cobbled the following together
DECLARE @cols AS NVARCHAR(MAX),
@query AS NVARCHAR(MAX)
select @cols = STUFF((SELECT ',' + QUOTENAME(YrMth)
from tbl_CRO_AverageAge where YrMth>=DATEADD(M,-11, DATEADD(DD,day(getdate())+1,GETDATE())) and
YrMth<=DATEADD(DD,day(getdate())+1,GETDATE()) ORDER BY YrMth
FOR XML PATH(''), TYPE
).value('.', 'NVARCHAR(MAX)')
,1,1,'')
--print @cols
set @query = 'create view [vw_CRO_AverageAge] AS SELECT ' + @cols + ' from
(
select YrMth, sum(AverageAge) over(partition by YrMth) Age FROM
tbl_CRO_AverageAge
where YrMth>=DATEADD(M,-11, DATEADD(DD,day(getdate())+1,GETDATE())) and
YrMth<=DATEADD(DD,day(getdate())+1,GETDATE())
) x
pivot
(
sum(Age)
for YrMth in (' + @cols + ')
) p '
print @query
execute @query
The output of the print can be run fine, but the execute returns the error. I've clearly made some simple error but I can't see it, as I'm not familiar at all with this sort of dynamic code. Is what I'm attempting possible in this manner, or have I gone about it all wrong?
Aucun commentaire:
Enregistrer un commentaire