我想要过滤两个参数,如果competitorID为null或为零,那么我应该针对另一个表中的所有竞争对手id过滤该集合,否则我应该针对competitorID进行过滤。
我写了以下内容,但它是错误的,因为它过滤了所有竞争对手。
SELECT
*
FROM DashboardDataCache AS d
WHERE ISNULL ( @CompetitorID , 0 ) = 0
OR d.CompetitorID IN (
SELECT
Value
FROM dbo.SessionFilters
WHERE SessionID = @SessionID
AND field IN ( 'competitor' , 'article_competitor' )) ;
答案 0 :(得分:1)
尝试更改您的查询,如下所示:
SELECT
*
FROM DashboardDataCache AS d
-- Filter by ID if @CompetitorID is not null
WHERE (@CompetitorID IS NOT NULL AND d.CompetitorID = @CompetitorID)
-- Otherwise, filter using SELECT
OR (@CompetitorID IS NULL AND d.CompetitorID IN (
SELECT Value
FROM dbo.SessionFilters
WHERE SessionID = @SessionID
AND field IN ( 'competitor' , 'article_competitor' )));
答案 1 :(得分:0)
尝试这样:
SELECT
*
FROM DashboardDataCache AS d
WHERE (ISNULL ( @CompetitorID , 0 ) = 0 and d.CompetitorID = @CompetitorID)
OR (ISNULL ( @CompetitorID , 0 ) != 0
AND d.CompetitorID IN (
SELECT
Value
FROM dbo.SessionFilters
WHERE SessionID = @SessionID
AND field IN ( 'competitor' , 'article_competitor' ))) ;