简体   繁体   中英

Case statement with “where in” clause

I have a scenario whereby I need to use multiple values in my where clause if a param passed to the query is 99999 otherwise I just use the param itself. I am using "IN" as part of the where clause but I get the following error "Incorrect syntax near the keyword 'CASE'". Any one provide an alternative to the incorrect query that will get me the results I need?

DECLARE @IPD_NEWS_TYPE_PARAM decimal (18,0)
 SET @IPD_NEWS_TYPE_PARAM = 99999

SELECT 
    n.id,
    n.headline,
    n.news_type_id
FROM news n
WHERE n.news_type_id IN
CASE WHEN @IPD_NEWS_TYPE_PARAM = 99999 THEN (1,2,3,4,5)
ELSE
(@IPD_NEWS_TYPE_PARAM)
END

Perhaps you want:

DECLARE @IPD_NEWS_TYPE_PARAM decimal (18,0)
 SET @IPD_NEWS_TYPE_PARAM = 99999

SELECT 
    n.id,
    n.headline,
    n.news_type_id
FROM news n
WHERE (n.news_type_id IN ('1','2','3','4','5') AND @IPD_NEWS_TYPE_PARAM = 99999) 
   OR (n.news_type_id = @IPD_NEWS_TYPE_PARAM AND @IPD_NEWS_TYPE_PARAM <> 99999)

Use an IF statement:

DECLARE @IPD_NEWS_TYPE_PARAM decimal (18,0)
 SET @IPD_NEWS_TYPE_PARAM = 99999

IF (@IPD_NEWS_TYPE_PARAM = 99999) 
    SELECT 
        n.id,
        n.headline,
        n.news_type_id
    FROM news n
    WHERE n.news_type_id IN (1,2,3,4,5)
ELSE
    SELECT 
        n.id,
        n.headline,
        n.news_type_id
    FROM news n
    WHERE n.news_type_id = @IPD_NEWS_TYPE_PARAM

You can use a CASE expression to return a value to be subsequently tested, eg:

SELECT 
    n.id,
    n.headline,
    n.news_type_id
FROM news n
WHERE CASE
  WHEN @IPD_NEWS_TYPE_PARAM = 99999 THEN
    CASE WHEN n.news_type_id IN (1,2,3,4,5) THEN 1 ELSE 0 END
  WHEN @IPD_NEWS_TYPE_PARAM = n.news_type_id THEN 1
  ELSE 0
  END = 1

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM