替代在ON子句中使用IIF以提高可读性

时间:2017-02-22 18:37:38

标签: sql sql-server select iif

我的同事发现在以下上下文中使用IIF很难理解。

是否有更易读的替代方法?

DROP TABLE IF EXISTS #Cas;
CREATE TABLE #Cas( OP VARCHAR(10), BR  VARCHAR(10), SCORE INT)
INSERT INTO #Cas
    values
        ('A','X', 10),
        ('A','Y', 5),
        ('B','J', 6),
        ('C','Q', 50)

DROP TABLE IF EXISTS #Target;
CREATE TABLE #Target( OP VARCHAR(10), BR  VARCHAR(10) )
INSERT INTO #Target
    values
        ('A','ALL')

SELECT  C.OP,
        SUM(C.SCORE)
FROM    #Cas C
        INNER JOIN #Target T
            ON 
            C.OP = T.OP AND
            C.BR = IIF(T.BR = 'ALL', C.BR, T.BR)
GROUP BY C.OP

1 个答案:

答案 0 :(得分:1)

我通常使用NULL来识别特定情况(f.e。" all")。因此,代码可能如下所示:

backgroundWorker1.DoWork += (senderWorker, e) =>
{
    try
    {
        // do something that might throw an exception
    }
    catch(Exception exception)
    {
        e.Result = exception; // this result is passed on to RunWorkerCompleted event
    }
}