2

有没有更好(更有效)的方式来编写这个查询?似乎应该有一种方法可以只用一个UNION.

询问:

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))

最终,我需要我的结果集有 2 列(PropertyKeyPropertyValue)。列中的值PropertyKey将是我表中列的名称,列中的值PropertyValue将是相应的值。

UNION如果我总是从同一张表中选择,是否可以只用一个来写这个?

4

1 回答 1

3

如果您有权访问该UNPIVOT功能,则可以通过以下方式使用它:

select PropertyKey, PropertyValue
from yourtable
unpivot
(
  PropertyValue
  for PropertyKey in (Value1, Value2, Value3) -- list other columns here
) unpiv

要记住的关键部分UNPIVOT是数据类型必须相同,因此您可能必须转换数据类型:

select PropertyKey, PropertyValue
from
(
    select CAST(value1 as varchar(10)), 
         CAST(value1 as varchar(10)), ...
    from yourtable
) src
unpivot
(
  PropertyValue
  for PropertyKey in (Value1, Value2, Value3) -- list other columns here
) unpiv

您甚至可以动态执行此操作,这将在运行时获取要转换的列列表:

DECLARE @colsUnpivot AS NVARCHAR(MAX),
    @query  AS NVARCHAR(MAX)    

select @colsUnpivot = stuff((select ','+quotename(C.name)
         from sys.columns as C
         where C.object_id = object_id('yourtable')
         for xml path('')), 1, 1, '')

set @query 
  = 'select PropertyKey, PropertyValue
     from yourtable
     unpivot
     (
        PropertyValue
        for PropertyKey in ('+ @colsunpivot +')
     ) u'

exec(@query)

如果你被卡住了,使用你当前的版本,那么我会稍微改变它并使用 aUNION ALL而不是UNION

SELECT 'Value1' as PropertyKey, Value1 PropertyValue
FROM MyTable
UNION ALL
SELECT 'Value2' as PropertyKey, Value2 PropertyValue
FROM MyTable
于 2012-12-17T20:22:47.387 回答