A SQL Statement with the Resultset Flopped

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 rowsetselect @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 selectionselect @colName='',@colId=1 create table #tmp (cName varchar(50))--add value columns for number of records returnedSelect @sql = 'Declare @cols smallint, @sql varchar(7000);Select @cols=count(*) From ' + @tblNameIf Len(@cond)>0	select @sql = @sql + ' Where ' + @condselect @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 onwhile @colname is not nullbegin	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)endSelect * from #tmpdrop table #tmp
See also  How IoT Tech Will Transform Logistics

About Our Editorial Process

At DevX, we’re dedicated to tech entrepreneurship. Our team closely follows industry shifts, new products, AI breakthroughs, technology trends, and funding announcements. Articles undergo thorough editing to ensure accuracy and clarity, reflecting DevX’s style and supporting entrepreneurs in the tech sphere.

See our full editorial policy.

About Our Journalist