0
UserID  | UserName  | 534 more columns -->
1       | John      | 534 more values  -->

I'm looking for this output from only about 78 of these columns:

Column  | Value 
UserID  | 1
UserName| John
+78 more rows
0

1 Answer 1

6

This is called unpivoting and I like to use apply:

select v.*
from t cross apply
     (values ('UserId', t.UserId),
             ('UserName', t.UserName)
             . . .
     ) v(column, value);

Do note that this assumes that all the columns have the same type.

apply implements what is technically called a "lateral join". There are other ways to implement this logic -- using union all or unpivot.

However, lateral joins are quite powerful and unpivoting is a good introduction to using them.

Sign up to request clarification or add additional context in comments.

3 Comments

From your perspective is this approach better than just repeated union statements:
Or better yet, could i approach this by building a "Column" table with all the columns i want to select and utilize sys.tables and sys.columns?
I accepted as is, this works for what I need. I'll just have 78 value pairs. Thank you sir.

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.