带连接和联合的动态select语句

时间:2015-06-23 11:10:08

标签: sql sql-server sql-server-2008-r2

我想使用存储过程准备动态select with joinselect with union语句。对此我有 以下数据。

我有两张桌子:

:Test1

select * from test1;
a   b
------
A   B
C   D
E   F

:Test1

select * from test2;
a   b
------
A   B
C   D

注意:现在我想将JoinsUnion同时应用于这些表格(可能还有更多表格) 存储过程。我创建了演示存储过程,如下所示:

CREATE PROCEDURE Pro_Test
@Columns VARCHAR(100), --Columns to display
@Tables VARCHAR(1000), --Two or More tables names may pass here
@JoinORUnion VARCHAR(50), --Join or Union the tables
@IfJoinOnColumn VARCHAR(50) ---If join has pass then ON which column

AS

DECLARE @query VARCHAR(MAX) 

    IF @JoinORUnion = 'Inner Join'
    BEGIN

        SET @query = '';    ---Here want to prepare select with join statement

        EXEC(@query);

    END

    ELSE IF @JoinORUnion = 'Union all'
    BEGIN

        SET @query = '';    ---Here want to prepare select with union statement

        EXEC(@query);

    END

GO  

如果我通过:

EXECUTE Pro_Test
@Columns        = 'a,b',
@Tables         = 'Test1,Test2',
@JoinORUnion    = 'Inner Join',
@IfJoinOnColumn = 'a';

然后声明应该是:

select test1.a,test1.b from test1
INNER JOIN 
test2 ON test1.a = test2.a;

结果:

a   b
------
A   B
C   D   

如果我通过:

EXECUTE Pro_Test
@Columns        = 'a,b',
@Tables         = 'Test1,Test2',
@JoinORUnion    = 'Union all',
@IfJoinOnColumn = '';

然后声明应该是:

select a,b from test1
union all
select a,b from test2

结果:

a   b
------
A   B
C   D
E   F
A   B
C   D

0 个答案:

没有答案