1

我有两个要过滤的参数,如果竞争者ID 为空或零,那么我应该根据另一个表中的所有竞争者ID 过滤该集合,否则我应该过滤竞争者ID。

我写了以下内容,但这是错误的,因为它过滤了所有竞争对手。

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' )) ;
4

2 回答 2

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' )));
于 2013-11-06T11:14:50.763 回答
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' ))) ;
于 2013-11-06T11:14:33.170 回答