Need to modify it slightly to fit your requirements. but this is my solution to rotate table vertically
Look like forum does not allow the drop statements for temporary tables, that was why it blew up (both on IE and firefox), so add 3 drop statements for temp tables at the end.
--create some test tables with test data for demo purpose
create table #question (questionId int identity(1,1), question varchar(100) )
create table #answer (answerId int identity(1,1), questionId int, answer varchar(100))
insert into #question(question)
select 'You are old?' union all
select 'You are smart?' union all
select 'You are rich?' union all
select 'You are loved?'
insert into #answer(questionId, answer)
select 1,'True' union all
select 2,'False' union all
select 3,'False'
--retrieve desired data
create table #temp (fieldName varchar(100),fieldValue varchar(100), sortOrder int identity(1,1) )
insert into #temp(fieldName,fieldValue)
exec ('select question, answer from #answer right join #question on #answer.questionid=#question.questionId where 1=1');
--generate sql statement to rotate table dynamically
declare @sql as varchar(8000)
set @sql = 'select ';
select @sql = @sql + '[' + fieldName+']=isnull((select fieldValue from #temp where fieldName='''+fieldName+'''),null),'
from #temp
order by sortOrder
set @sql = SUBSTRING(@sql, 1, LEN(@sql)-1)
print @sql
exec(@sql)