0

I am trying to convert columns into rows using cursors. I know people say cursors are the right thing to do. I know we can use pivot to achieve this. But the problem is that client needs it as cursors with a for loop. Not really sure as to why they need it that way but looks like its easier for them to understand the code.

Table A

ID  FieldA   FieldB  FieldC 
 1   abc      123     xyz

This needs to be converted to

ID  Field0
 1   abc
 1   123
 1   xyz

Any pointers on how to achieve it could be helpful

Thanks

Prady

4
  • I am sorry.. it should be unpivot... Yeah i know its pretty baffling some feel cursor to be simple... its just way too complicated for me :( Commented May 10, 2011 at 12:25
  • 1
    It is UNPIVOT you would need rather than PIVOT and I cannot see how cursor code would be anything but less simple. The basic code you need is SELECT ID,Field0 FROM Table1 UNPIVOT(Field0 FOR FieldName IN (FieldA,FieldB,FieldC)) U Commented May 10, 2011 at 12:26
  • 1
    What the client wants isn't necessarily what they need...bear that in mind. I can tell you I need a new server machine that runs on 80486 cpus, and you can do it, but it's not the best solution. Commented May 10, 2011 at 12:46
  • I suspect it is an interview/teaching task rather then real one. Commented May 10, 2011 at 12:52

1 Answer 1

3

Why not simply:

select ID, FieldA as Field0 from TableA
union all
select ID, FieldB from TableA
union all
select ID, FieldC from TableA
Sign up to request clarification or add additional context in comments.

1 Comment

Thats pretty interesting... Didnt know it could be so simple..But client seems to be adamant on cursors

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.