I want to fetch data from table table variable @questionset as shown in fig and insert into #tempqset .

1 year ago 6 Replies
SM
Sukdev Mandal
7 years ago

Guys!!!

I want to fetch data from table table variable @questionset as shown in fig and insert into #tempqset .

Plz provide optimise query to solve it out

0 Likes

Replies

Rakesh Rawat 7 years ago

Best optimise way is to use a union all statement and dump into temp table as below

Select * into #temp From ( Selection questionid, optionA from @tbl Union All Selection questionid, optionB from @tbl Union All Selection questionid, optionC from @tbl Union All Selection questionid, optionD from @tbl Union All Selection questionid, optionE from @tbl Union All Selection questionid, answer from @tbl )Base

2 Likes
Sukdev Mandal 7 years ago

Rakesh Rawat excellent

But I am getting error by direct inserting select data into temp table

So using cte m inserting data into temp table

Thanks for ur valuable information

1 Like
Rakesh Rawat 7 years ago

First you have to create a table variable and insert your data into it and at a single sort you have to execute the complete code including creation of table variable as tbl vrbl has a scope with in the batch only

1 Like
Manoj Pandey 7 years ago

you need to use UNPIVOT operators to rotate the columns into rows, like this (not tested):

SELECT QuestionID, Option FROM (SELECT QuestionID, Option1, Option2, Option3, Option4, Option5, Answer FROM @tableVar) p UNPIVOT (Option FOR QuestionID IN (Option1, Option2, Option3, Option4, Option5, Answer) )AS unpvt;

Check here: https://sqlwithmanoj.com/2009/04/12/ms-sql-server-2005-new-feature-pivot-and-unpivot/

3 Likes
Sukdev Mandal 7 years ago

Manoj Pandey thanks its also great advance approach ...

0 Likes
Sukdev Mandal 7 years ago

Rakesh Rawat you are right !! Actually I have already inserted data into temp table before for another task

That's why I was unable to fetch data again.

1 Like