Is there a better (more efficient) way to write this query? It seems like there should be a way to write it with only one UNION.
Query:
SELECT 'Value1' as PropertyKey, PropertyValue=(SELECT Value1 FROM MyTable WITH (NOLOCK))
UNION
SELECT 'Value2' as PropertyKey, PropertyValue=(SELECT Value2 FROM MyTable WITH (NOLOCK))
UNION
SELECT 'Value3' as PropertyKey, PropertyValue=(SELECT Value3 FROM MyTable WITH (NOLOCK))
UNION
...
SELECT 'Value100' as PropertyKey, PropertyValue=(SELECT Value100 FROM MyTable WITH (NOLOCK))
Ultimately, I need my result set to have 2 columns (PropertyKey, and PropertyValue). The values in the PropertyKey column will be the names of the columns in my table, and the values in the PropertyValue column will be the corresponding values.
Is it possible to write this with only one UNION if I’m always selecting from the same table?
If you have access to the
UNPIVOTfunction you can use it the following way:The key piece to keep in mind with an
UNPIVOTis the datatypes must be the same, so you might have to convert the datatypes:You can even perform this dynamically, which will get the list of columns to transform at run-time:
If you are stuck, using your current version then I would alter it slightly and use a
UNION ALLinstead of theUNION: