如何在存储过程中使用多个select语句作为Resultset中的列

时间:2014-09-02 22:13:43

标签: sql sql-server-2005 stored-procedures

我有一个存储过程,其中包含多个sql语句,

SELECT X,ID FROM TABLE1
SELECT Y,ID FROM TABLE2 
SELECT Z,ID FROM Table3 

当我执行上述声明表格时 我的结果集应该是

enter image description here

ID,X,Y,Z将列和1,10,20,30将是第1行的值,6,40,50,60将是第二行的值,...继续 我正在使用SQL SERVER 2005

是否可以这样做?

1 个答案:

答案 0 :(得分:3)

如果每张表中只有1行,您可以执行以下操作:

select
    (select X from table1) X,
    (select Y from table2) Y,
    (select Z from table3) Z;

Example SQLFiddle

对于您的第二个示例,您只能使用join

select
    t1.id,
    t1.X,
    t2.Y,
    t3.Z
from
    table1 t1
        inner join
    table2 t2
        on t1.id = t2.id
        inner join
    table t3
        on t2.id = t3.id;

如果这些表确实是更大的查询的占位符,那么使用with

可能会更容易阅读
;with t1 as (
    select id, X from table1
), t2 as (
    select id, Y from table2,
), t3 as (
    select id, Z from table3
) select
    t1.id,
    t1.X,
    t2.Y,
    t3.Z
from
    t1
        inner join
    t2
        on t1.id = t2.id
        inner join
    t3
        on t2.id = t3.id;