No need for loop, you can simply use the UNPIVOT
table operator to do this:
INSERT INTO temp
SELECT
QNO,
val
FROM Testseed AS t
UNPIVOT
(
val
FOR col IN([QA1], [QA2], [QA3], [QA4])
) AS u;
For example, if you have the following sample data:
| QNO | QTEXT | QA1 | QA2 | QA3 | QA4 |
|-----|-------|-----|-----|-----|-----|
| 1 | q1 | a | b | c | d |
| 2 | q2 | b | c | d | e |
| 3 | q3 | e | a | b | c |
| 4 | q4 | a | c | d | e |
| 5 | q5 | c | d | e | a |
The previous query will fill the temp
table with:
| QNO | QA |
|-----|----|
| 1 | a |
| 1 | b |
| 1 | c |
| 1 | d |
| 2 | b |
| 2 | c |
| 2 | d |
| 2 | e |
| 3 | e |
| 3 | a |
| 3 | b |
| 3 | c |
| 4 | a |
| 4 | c |
| 4 | d |
| 4 | e |
| 5 | c |
| 5 | d |
| 5 | e |
| 5 | a |
The UNPIVOT
table operator, will convert the values of the four columns [QA1], [QA2], [QA3], [QA4]
into rows, only one row.
Then you can put that query inside a stored procedure.