我有一个场景,如果传递给查询的参数是99999,我需要在where子句中使用多个值,否则我只使用param本身。我使用“IN”作为where子句的一部分,但我得到以下错误“关键字'CASE'附近的语法不正确”。 任何一个提供替代不正确的查询,将获得我需要的结果?
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
答案 0 :(得分:5)
也许你想要:
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)
答案 1 :(得分:0)
使用IF语句:
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
答案 2 :(得分:0)
您可以使用CASE
表达式返回要随后测试的值,例如:
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