sql server - Lost my column headings SQL -
i had following dummy code (you can use test):
use tempdb; go create table dbo.products ( productid varchar (50), period varchar (6), value decimal (15, 2) ); insert dbo.products values ('north', '201201', 100), ('south', '201202', 500); select productid, period, value dbo.products p; declare @columns nvarchar(max), @sql nvarchar(max); set @columns = n''; select @columns += n', p.' + quotename(period) (select p.period dbo.products p group p.period) x; set @sql = n' select * ( select productid, period, value dbo.products p ) j pivot ( sum(value) period in (' + stuff(replace(@columns, ', p.[', ',['), 1, 1, '') + ') ) p;'; print @sql; exec sp_executesql @sql; drop table dbo.products
it generated output contained nulls - column headings present though.
to remove nulls, code looks this:
use tempdb; go create table dbo.products ( productid varchar (50), period varchar (6), value decimal (15, 2) ); insert dbo.products values ('north', '201201', 100), ('south', '201202', 500); select productid, period, value dbo.products p; declare @columns nvarchar(max), @selectlist nvarchar(max), @sql nvarchar(max); set @columns = n''; select @columns += n', p.' + quotename(period) (select p.period dbo.products p group p.period) x; set @selectlist = n''; select @selectlist += n', isnull(' + quotename(period) + ', 0)' (select p.period dbo.products p group p.period) x; print '@selectlist = ' + @selectlist set @selectlist = stuff(@selectlist, 1, 1, ''); set @sql = n' select productid, ' + @selectlist + ' ( select productid, period, value dbo.products p ) j pivot ( sum(value) period in (' + stuff(replace(@columns, ', p.[', ',['), 1, 1, '') + ') ) p;'; print '@sql = ' + @sql; exec sp_executesql @sql;
but column headings show [no column name]?
how headings back?
good afternoon! when setting @selectlist variable sure specify alias column names "as" ...
set @selectlist = n''; select @selectlist += n', isnull(' + quotename(period) + ', 0) ' + quotename(period) (select p.period dbo.products p group p.period) x; print '@selectlist = ' + @selectlist set @selectlist = stuff(@selectlist, 1, 1, '');
Comments
Post a Comment