您好我有下面的查询,我需要在class中使用if语句。
Alter procedure dbo.GetName(@id int, @statusDate VARCHAR(50))
begin
select id, name
from customer
where id = @id and
IF(@statusDate = 'Active')
status > GetDate()
ELSE
status < GetDate()
end
此状态是customer表中类型为date的列 @statusDate是我将要传递的参数(活动或非活动) 如果在第二个'和'之后有效,我必须获得状态&gt; GetDate()今天的日期其他状态&lt; GETDATE()。
答案 0 :(得分:3)
你不能在where子句中有if子句,但是你可以重构你在哪里做同样的事情。
试试这个
ALTER PROCEDURE dbo.GetName(@id int, @statusDate VARCHAR(50))
AS
SELECT id, name
FROM customer
WHERE id = @id AND
(
(@statusDate = 'Active' AND status > GetDate()) OR
(@statusDate = 'Inactive' AND status < GetDate()) OR
(@statusDate IS NULL)
)
答案 1 :(得分:0)
我认为你可以摆脱if语句重构你的SQL:
SELECT id, name
FROM customer
WHERE id = @id and
(@statusDate = 'Active' and status > GetDate()) or (@statusDate = 'Active' and status < GetDate())
答案 2 :(得分:0)
在SQL中,您将使用布尔OR运算符来实现相同的效果:
alter procedure dbo.GetName(@id int, @statusDate VARCHAR(50))
begin
select id, name
from customer
where id = @id
and (
(@statusDate = 'Active' and status >= GetDate())
or (@statusDate <> 'Active' and status < GetDate())
)
答案 3 :(得分:0)
有时,像Gavin和Massimiliano这样的OR逻辑会导致性能下降。这导致人们尝试了许多选项,例如以下......
IF (@statusDate = 'Active')
SELECT id, name FROM customer WHERE id = @id AND status > GetDate()
ELSE
SELECT id, name FROM customer WHERE id = @id AND status < GetDate()
SELECT id, name FROM customer
WHERE id = @id
AND status > CASE WHEN @statusDate = 'Active' THEN GetDate() ELSE 0 END
AND status < CASE WHEN @statusDate = 'Active' THEN '99991231' ELSE GetDate() END
SELECT id, name FROM customer WHERE id = @id AND status > GetDate() AND @statusDate = 'Active'
UNION ALL
SELECT id, name FROM customer WHERE id = @id AND status < GetDate() AND @statusDate = 'Inactive'
答案 4 :(得分:0)
select id, name
from customer
where id = @id
and 'T' = case
when @statusDate = 'Active' then case
when status > GetDate() then 'T'
end
else case
when status < GetDate() then 'T'
end
end;