Login | Register   
LinkedIn
Google+
Twitter
RSS Feed
Download our iPhone app
TODAY'S HEADLINES  |   ARTICLE ARCHIVE  |   FORUMS  |   TIP BANK
Browse DevX
Sign up for e-mail newsletters from DevX


Tip of the Day
Language: SQL
Expertise: Advanced
Jul 13, 2004

A SQL Statement with the Resultset Flopped

I got a request from a developer the other day to produce a SQL statement with the resultset flopped. In other words, he wanted the rows to appear as columns and the columns to appear as rows. What's more, he wanted the names of the rows to appear in the first column.

Say you had a resultset like this:


Col1,Col2,Col3 A,B,C D,E,F
He wanted to see the information like this:
 
ColName, Value1, Value2,... Col1,A,D Col2,B,E Col3,C,F 
The following code shows how I did this. I wouldn't use this to return an extremely large recordset, but it is interesting to work with anyway.

declare @colName varchar(50), @colId smallint, @tblName varchar(50)
declare	@sql varchar(1000), @cond varchar(6000)

--user selection criteria These are the only variables you need to change
		--Name OF Table		--Limiting Condition on rowset
select @tblName='some table', 
@cond = ' some limiting condition for the table ie (ID=75) or (ID between 1 and 7)'
--I would recommend that you not return more than 100 rows

--Begin selection
select @colName='',@colId=1 

create table #tmp (cName varchar(50))
--add value columns for number of records returned

Select @sql = 'Declare @cols smallint, @sql varchar(7000);Select @cols=count(*) From ' + @tblName
If Len(@cond)>0
	select @sql = @sql + ' Where ' + @cond

select @sql = @sql + ';
	while @cols > 0
	begin
		select @sql = ''alter table #tmp add [Val'' + cast(@cols as varchar) + ''] varchar(50)''
		Exec(@sql)
		select @cols = @cols - 1
	End'

exec( @sql)


set nocount on
while @colname is not null
begin
	select @colname = col_name(object_id(@tblName),@colID)
	Select @colID = @colid + 1
	select @sql = 'declare @retVal varchar(6000);set @retVal = '''';
		update ' + @tblName + ' set @retVal=@retVal + '','' + substring(cast (' + @colname + ' as varchar),1,50)'
	if len(@cond) > 0 
		select @sql = @sql + ' Where ' + @cond
	select @sql = @sql + ';
		select @retval = replace(substring(@retVal,2,len(@retVal)),'','','''''','''''')
		Select @retVal = '''''''' + @retVal + ''''''''
		declare @sql varchar(7000);
		select @sql = ''Insert Into #tmp Values('''''+ @colName + ''''','' + @retVal + '')''
	if len(@sql) > 0 Exec (@sql)
'
	execute (@sql)
end

Select * from #tmp
drop table #tmp
Steve Turquette
 
Comment and Contribute

 

 

 

 

 


(Maximum characters: 1200). You have 1200 characters left.

 

 

Sitemap
Thanks for your registration, follow us on our social networks to keep up-to-date