TSQL嵌套IF逻辑

时间:2014-06-09 14:24:32

标签: sql sql-server tsql

我有一个查询,我用来将数据提取到我的页面。目前,您可以在我的报告中选择“位置”并显示该位置的数据。我想添加一个“全局”选项,这样当选择该选项时,查询将返回所有数据。

这是我按位置查询数据的当前工作SP:

IF (@action = 'segment')

    BEGIN
        SELECT   B.[segmentName],
                 count(A.[segmentID]) AS total,
                 A.[meetingID],
                 C.[center]
        FROM     Focus_Meetings_Segments AS A
                 INNER JOIN
                 Focus_Segments AS B
                 ON A.[segmentID] = B.[id]
                 JOIN Focus_Meetings as C
                 ON C.[id] = A.[meetingID]
        WHERE C.[center] = @location
        GROUP BY B.[segmentName], A.[meetingID], C.[center]
        ORDER BY total DESC
        FOR      XML PATH ('segment'), TYPE, ELEMENTS, ROOT ('root');
    END
ELSE

她是查询对所有数据的处理方式:

IF (@action = 'segment')

    BEGIN
        SELECT   B.[segmentName],
                 count(A.[segmentID]) AS total
        FROM     Focus_Meetings_Segments AS A
                 INNER JOIN
                 Focus_Segments AS B
                 ON A.[segmentID] = B.[id]
        GROUP BY B.[segmentName], A.[segmentID]
        ORDER BY total DESC
        FOR      XML PATH ('segment'), TYPE, ELEMENTS, ROOT ('root');
    END
ELSE

有没有办法用案例逻辑内联或者可以像下面那样执行嵌套的if语句?

IF (@action = 'segment')
    IF (@location = 'global')

1 个答案:

答案 0 :(得分:1)

您不需要两个不同的语句。只需更改Where子句,使其基于@location

的值为条件
 Where C.[center] = coalesce(@location, C.[center])

然后只需要传递一个null就可以了。

注意:如果有时加入B可能会失败,请将其设为外连接。

    SELECT B.[segmentName],
       count(A.[segmentID]) AS total,
        A.[meetingID],
         C.[center]
    FROM  Focus_Meetings_Segments AS A
       JOIN Focus_Segments B
          ON A.[segmentID] = B.[id]
       Left JOIN Focus_Meetings as C
          ON C.[id] = A.[meetingID]
             And C.[center] = coalesce(@location, C.[center])
    GROUP BY B.[segmentName], A.[meetingID], C.[center]
    ORDER BY total DESC
    FOR  XML PATH ('segment'), TYPE, ELEMENTS, ROOT ('root');