Union All With if / else T-SQL

时间:2010-11-26 20:02:42

标签: sql tsql

我想知道如何使用IF / ELSE语句获得UNION ALL。

例如:

SELECT * FROM A
UNION ALL
SELECT * FROM B
UNION ALL

IF @type = 1
   BEGIN
      SELECT * FROM C
   END
ELSE
   BEGIN
      SELECT * FROM D
   END

UNION ALL

SELECT * FROM E

我收到语法错误。

2 个答案:

答案 0 :(得分:15)

SELECT * FROM A 
UNION ALL 
SELECT * FROM B 
UNION ALL 
SELECT * FROM C WHERE @type = 1
UNION ALL
SELECT * FROM D WHERE @type <> 1 OR @type IS NULL
UNION ALL 
SELECT * FROM E ;

答案 1 :(得分:3)

一种方法是使用动态sql

首先构建查询字符串,然后执行它。这样你就可以完全控制

declare query nvarchar(max)
set query = 'SELECT * FROM A
             UNION ALL
             SELECT * FROM B
             UNION ALL '

IF @type = 1
BEGIN
set query = query + '
            SELECT * FROM C'
END
ELSE
BEGIN
set query = query + '
            SELECT * FROM D'
END
set query = 'UNION ALL
             SELECT * FROM E'

exec(query)