SQL代码简化了ISNULL或COALESCE协助

时间:2015-06-01 17:43:51

标签: sql sql-server-2012

所以我有这个存储过程,我被要求通过使用ISNULL或COALESCE来简化它,但我似乎无法使其工作

CREATE PROCEDURE [GetCount]

    @Session NVARCHAR(7),
    @Activity BIT = true

AS

IF @Activity = 1 
BEGIN
      SELECT COUNT([user].[ActivityID]) AS [Count]
    FROM [ActivityListing] AS [act]
        INNER JOIN [ActivityListingDescriptions] AS [actDesc] 
            ON [act].[ActivityID] = [actDesc].[ActivityID]
    WHERE [act].[ListingSession] = @Session 
        AND [act].[ListingStatus] IN ('P','Q','N')
END
ELSE 
    SELECT COUNT([user].[ActivityID]) AS [Count]
    FROM [ActivityListing] AS [act]
        INNER JOIN [ActivityListingDescriptions] AS [actDesc] 
            ON [act].[ActivityID] = [actDesc].[ActivityID]
    WHERE [act].[ListingSession] = @Session 
        AND [act].[ListingStatus] NOT IN ('')

我在这里遇到的问题是,它不是我传递的值,而是我正在更改查询本身,一个是WHERE ... IN而另一个是WHERE ... NOT IN所以它不会允许我将查询写为返回的结果。还有另一种方法可以完成简化代码的任务吗?

1 个答案:

答案 0 :(得分:2)

您可以将ISNULL条件合并到单个查询中,而不是使用COALESCEWHERE

CREATE PROCEDURE [GetCount]
    @Session NVARCHAR(7),
    @Activity BIT = true
AS
    SELECT COUNT([user].[ActivityID]) AS [Count]
    FROM [ActivityListing] AS [act]
        INNER JOIN [ActivityListingDescriptions] AS [actDesc] 
            ON [act].[ActivityID] = [actDesc].[ActivityID]
    WHERE [act].[ListingSession] = @Session 
        AND ((@Activity = 1 AND [act].[ListingStatus] IN ('P','Q','N') ) 
            OR (@Activity <> 1 AND [act].[ListingStatus] NOT IN ('')))

如果@Activity的值为1,则将执行条件的IN部分,如果除了1之外的任何其他内容,则将执行NOT IN条件