SQL IF / ELSE语句

时间:2018-11-12 22:35:16

标签: sql sql-server tsql if-statement

我有一个Select语句,需要在其中添加IF / ELSE语句,

IF @P_COUNT = 'X' 
    show the Count(*) FROM SELECT statement 
ELSE 
    I need to return table from the SELECT statement results 

目前这是我所拥有的,但无法正常工作。

@P_COUNT            VARCHAR(1)

IF @P_COUNT = 'X' 
    SELECT COUNT(*) 
    ELSE SELECT * FROM (
   (SELECT ... UNION ... ) AS A
    LEFT JOIN 
   (SELECT A, B, C, D FROM Table_1) AS B
    ON WHERE A.XX = B.XX
    LEFT JOIN 
   (SELECT A, B, C, D FROM Table_1) AS C
    ) AS D 

当前结果:

IF @P_COUNT = 'X', RESULT => 1 Expected => 26017
IF @P_COUNT = '', RESULT => returns proper Select statement.  

预先感谢您的帮助!

1 个答案:

答案 0 :(得分:4)

这是您想要的吗?

IF @P_COUNT = 'X' 
BEGIN
   SELECT COUNT(*) 
   FROM (
   (SELECT ... UNION ... ) AS A
    LEFT JOIN 
   (SELECT A, B, C, D FROM Table_1) AS B
    ON WHERE A.XX = B.XX
    LEFT JOIN 
   (SELECT A, B, C, D FROM Table_1) AS C
    ) AS D 
END
ELSE
BEGIN
   SELECT * FROM (
   (SELECT ... UNION ... ) AS A
    LEFT JOIN 
   (SELECT A, B, C, D FROM Table_1) AS B
    ON WHERE A.XX = B.XX
    LEFT JOIN 
   (SELECT A, B, C, D FROM Table_1) AS C
    ) AS D 
END;

您有两个独立的SELECT查询。他们每个人都需要一个FROM子句。