所以我有这个存储过程,我被要求通过使用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
所以它不会允许我将查询写为返回的结果。还有另一种方法可以完成简化代码的任务吗?
答案 0 :(得分:2)
您可以将ISNULL
条件合并到单个查询中,而不是使用COALESCE
或WHERE
:
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
条件