SQL Server-表行到数据字典转换

Sak*_*Ali 1 t-sql sql-server sql-server-2008

我正在使用SQL Server 2008.我有两个表,Table1和Table2如下所示.

表格1

ID  Col1  Col2  Col3
--  ----  ----  ----
 1     X     Y     Z
Run Code Online (Sandbox Code Playgroud)

表2

ID  Col1  Col2  Col3
--  ----  ----  ----
 1     1     2     3
Run Code Online (Sandbox Code Playgroud)

我想写一个存储过程,返回如下所示的结果.并且必须在不使用游标的情况下实现此结果.

结果

Key  Value  
---  -----
  X      1
  Y      2  
  Z      3
Run Code Online (Sandbox Code Playgroud)
Edited:
I required one result set.
Both IDs are parameter of my Store Procedure.

Tar*_*ryn 5

由于您使用的是SQL Server 2008,因此可以使用CROSS APPLY和VALUES来取消数据.您可以先在id列上加入两个表,然后将其取消键入key/ valuecolumns:

select [key], value
from
(
  select t1.col1, t2.col1 t2_col1, 
    t1.col2, t2.col2 t2_col2, 
    t1.col3, t2.col3 t2_col3
  from table1 t1
  inner join table2 t2
    on t1.id = t2.id
) src
cross apply
(
  values
  (col1, t2_col1),
  (col2, t2_col2),
  (col3, t2_col3)
) c ([key], value);
Run Code Online (Sandbox Code Playgroud)

请参阅SQL Fiddle with Demo