Dynamic SQL SQL Server 2012 Get Result into a #temp table -
i using sql server 2012. final result @sql temp table.here code far. help.
if object_id ('tempdb.dbo.#my_dt_cte') not null drop table #my_dt_cte create table #my_dt_cte ([rowid] int not null identity (1,1) ,[yyyymm] int ) ; my_dt_cte ( select convert(int,convert(varchar(6),eomonth(getdate(),-1),112)) [yyyymm] union select convert(int,convert(varchar(6),eomonth(getdate(),-2),112)) [yyyymm] union select convert(int,convert(varchar(6),eomonth(getdate(),-3),112)) [yyyymm] union select convert(int,convert(varchar(6),eomonth(getdate(),-4),112)) [yyyymm] union select convert(int,convert(varchar(6),eomonth(getdate(),-5),112)) [yyyymm] union select convert(int,convert(varchar(6),eomonth(getdate(),-6),112)) [yyyymm] ) insert #my_dt_cte select [yyyymm] my_dt_cte order [yyyymm] desc; -- select * #my_dt_cte declare @columns nvarchar(max), @sql nvarchar(max); set @columns = n''; select @columns += n', p.' + quotename(yyyymm) (select p.yyyymm #my_dt_cte p group p.yyyymm) x; set @sql = n' select ' + stuff(@columns, 1, 2, '') + ' ( select p.yyyymm #my_dt_cte p ) j pivot ( count(yyyymm) yyyymm in (' + stuff(replace(@columns, ', p.[', ',['), 1, 1, '') + ') ) p;'; print @sql; exec sp_executesql @sql;
need bring result @sql temp table. 201605 201606 201607 201608 201609 201610
an easy way use global temporary table. can selected into
in dynamic sql scope automatically have desired schema , still available after exits.
set @sql = n' select ' + stuff(@columns, 1, 2, '') + ' ##globaltemp ( select p.yyyymm #my_dt_cte p ) j pivot ( count(yyyymm) yyyymm in (' + stuff(replace(@columns, ', p.[', ',['), 1, 1, '') + ') ) p;'; exec sp_executesql @sql; select * ##globaltemp
however can cause issues naming clashes if code ever executed concurrently.
it possible use local temp table code more involved involves creating temp table @ upper scope , using dynamic sql alter dynamically determined schema before inserting it.
create table #t ( dummy int ); set @sql = 'alter table #t add dummy2 int' + replace(replace(@columns, 'p.', ''), ']', '] int') + '; alter table #t drop column dummy, dummy2;' exec (@sql); set @sql = n' insert #t select ' + stuff(@columns, 1, 2, '') + ' ( select p.yyyymm #my_dt_cte p ) j pivot ( count(yyyymm) yyyymm in (' + stuff(replace(@columns, ', p.[', ',['), 1, 1, '') + ') ) p;'; exec sp_executesql @sql; select * #t
Comments
Post a Comment