Select 具有视图名称和列名称的视图的值

Select a value of a view with view name and column name

我有:

VIEW A 
uid name
10   test1
20   test2
30   test3
40   test4

我想要的:

ViewName  ColName Row Value   
View A    uid     1   10
View A    name    1   test1
View A    uid     2   20
View A    name    2   test2

您可以使用基于 view_A

上的子查询的联合
select  'View A', 'uid' colname, row_num,  uid value
from (
SELECT 
  ROW_NUMBER() OVER(ORDER BY uid ASC) AS row_num, uid, name
from view_A

)
UNION ALL 
select  'View A', 'name', row_num,  name
from (SELECT 
  ROW_NUMBER() OVER(ORDER BY uid ASC) AS row_num, uid, name
from view_A)
ORDER BY row_num, colname

您可以在 CTE 中分配行号,然后使用 UNION ALL 逆透视。

备注:

  • uid 看起来像整数数据类型,而 name 是字符串,因此您需要将 uid 转换为 VARCHAR else UNION ALL 将引发错误。

  • 显然 ViewName 在查询中被硬编码为 viewA

查询:

WITH cte AS (
    SELECT 'viewA' ViewName, uid, name, ROW_NUMBER() OVER(ORDER BY uid) rn FROM viewA
)
SELECT ViewName, 'uid' ColName, rn Row, CAST(uid AS varchar(50)) value FROM cte
UNION ALL SELECT ViewName, 'name' ColName, rn Row, name FROM cte
ORDER BY rn, ColName DESC

Demo on DB FIddle:

ViewName | ColName | Row | value
:------- | :------ | :-- | :------
viewA    | uid     | 1   | 10              
viewA    | name    | 1   | test1           
viewA    | uid     | 2   | 20              
viewA    | name    | 2   | test2           
viewA    | uid     | 3   | 30              
viewA    | name    | 3   | test3           
viewA    | uid     | 4   | 40              
viewA    | name    | 4   | test4           

你可以使用这个:

DECLARE @ViewName NVARCHAR(64) = 'ViewA'
DECLARE @Query NVARCHAR(MAX) = ''

SET @Query = ' 
SELECT  ' + '''' + @ViewName + + '''' + ' AS ViewName,
        C.[name] AS ColName,
        V.[name] AS [Value],
        DENSE_RANK() OVER( ORDER BY V.[Uid] ) AS [Row]
FROM    ' + @ViewName + ' AS V
        INNER JOIN sys.columns AS C ON C.object_id = OBJECT_ID(' + '''' + @ViewName + '''' + ')'
        print @Query

EXECUTE SP_EXECUTESQL @Query