我似乎无法使我的SP工作:
ALTER PROCEDURE [dbo].[TestSP]
@participant_role nvarchar(max) = null,
@active int,
@inactive int
AS
BEGIN
select * from participant_list where participant_role = ISNULL(@participant_role, participant_role)
and
case when @active = 0 then ((effective_end_date IS NULL) or (effective_end_date > CURRENT_DATE))
case when @inactive = 0 then ((effective_end_date IS NOT NULL) or (effective_end_date < CURRENT_DATE))
ELSE
--Return everything
END
如果@active为0,则发生的情况是,查询应包含条件((effective_end_date IS NULL) or (effective_end_date > CURRENT_DATE))
同样明智的是,如果@inactive为0,则条件应包括((effective_end_date IS NOT NULL) or (effective_end_date < CURRENT_DATE))
如果@active和@inactive都不是0,那么它应该返回所有内容(此部分没有条件)。我如何使它工作?
答案 0 :(得分:2)
似乎有一种特殊的痛苦,人们发现SQL的CASE
表达式似乎立即停止考虑更简单的布尔运算符:
select * from participant_list
where participant_role = ISNULL(@participant_role, participant_role)
and
(
(
@active = 0 and (
(effective_end_date IS NULL) or
(effective_end_date > CURRENT_DATE)
)
) or
(
@inactive = 0 and effective_end_date < CURRENT_DATE
) or
( @active = 1 and @inactive = 1)
)
答案 1 :(得分:1)
SELECT *
FROM mytable
WHERE ...
AND
CASE
WHEN @active = 0 AND ((effective_end_date IS NULL) or (effective_end_date > CURRENT_DATE)) THEN
1
WHEN @inactive = 0 AND ((effective_end_date IS NOT NULL) or (effective_end_date < CURRENT_DATE)) THEN
1
ELSE
1
END = 1
答案 2 :(得分:0)
select * from participant_list
where participant_role = ISNULL(@participant_role, participant_role)
and
(
(@active = 0 and (effective_end_date IS NULL or effective_end_date > CURRENT_DATE))
or
(@inactive = 0 and (effective_end_date IS NOT NULL or effective_end_date < CURRENT_DATE))
or
(@active != 0 and @active != 0)
)
答案 3 :(得分:0)
使用案例
select * from participant_list
where (@participant_role IS NOT NULL AND participant_role = @participant_role)
and 1 = (case when @active = 0 AND (effective_end_date IS NULL or (effective_end_date > GETDATE()))
then 1
when @inactive = 0 AND (effective_end_date IS NOT NULL or (effective_end_date < GETDATE()) )
then 1
WHEN @active = 0 AND @inactive = 0
THEN 1
else 0 end)