T-SQL中的条件联盟

时间:2011-06-02 11:03:52

标签: tsql sql-server-2008

目前我的查询如下:

-- Query 1
SELECT
    acc_code, acc_name, alias, LAmt, coalesce(LAmt,0) AS amt 
FROM 
    (SELECT 
        acc_code, acc_name, alias, 
        (SELECT 
            (SUM(cr_amt)-SUM(dr_amt)) 
        FROM 
            ledger_mcg l
        WHERE 
            (l.acc_code LIKE a.acc_code + '.%' OR l.acc_code=a.acc_code) 
        AND 
            fy_id=1 
        AND
            posted_date BETWEEN '2010-01-01' AND '2011-06-02') AS LAmt 
    FROM
        acc_head_mcg AS a 
    WHERE 
    (acc_type='4')) AS T1
WHERE 
    coalesce(LAmt,0)<>0

查询2与查询1相同,但查询2中的acc_type = '5'除外。查询2始终返回带有单行的结果集。现在,我需要两个查询的联合,即

Query 1 
UNION
Query 2

仅当查询2返回的amt小于0.否则,我不需要联合但只需要来自查询1的结果集。

我能想到的最好方法是创建一个参数化标量函数。我怎么能做到最好?

1 个答案:

答案 0 :(得分:5)

您可以将第一个查询的结果存储到临时表中,然后,如果该表不为空,则执行另一个查询。

IF OBJECT_ID('tempdb..#MultipleQueriesResults') IS NOT NULL
  DROP TABLE #MultipleQueriesResults;

SELECT
    acc_code, acc_name, alias, LAmt, coalesce(LAmt,0) AS amt 
INTO #MultipleQueriesResults
FROM 
    (SELECT 
        acc_code, acc_name, alias, 
        (SELECT 
            (SUM(cr_amt)-SUM(dr_amt)) 
        FROM 
            ledger_mcg l
        WHERE 
            (l.acc_code LIKE a.acc_code + '.%' OR l.acc_code=a.acc_code) 
        AND 
            fy_id=1 
        AND
            posted_date BETWEEN '2010-01-01' AND '2011-06-02') AS LAmt 
    FROM
        acc_head_mcg AS a 
    WHERE 
    (acc_type='4')) AS T1
WHERE 
    coalesce(LAmt,0)<>0;

IF NOT EXISTS (SELECT * FROM #MultipleQueriesResults)
  … /* run Query 2 */