我正在创建一个存储过程,该存储过程从存储项目资金的表中获取值(他们的id,他们的目标以及他们到目前为止收到的内容)
proc将返回已完全资助的项目ID或未提供参数@QueryType
的项目ID,但我不知道如何在where
中添加if条件,I只在陈述的select
部分使用过它们。
这是我到目前为止所做的,但它只是给了我INCORRECT SYNTAX
第一个案例:
--create proc Projects.GetFundedProjects -- Projects that have reached their goal
create proc Projects.GetFundedProjects
(@QueryType int
)
as
begin
select * from Stats.FundedProjectsToday
CASE
WHEN @QueryType = 1 -- Projects that reached their goal
THEN
where AUReceived=>ProjectGoal
WHEN @QueryType = 2 -- Projects that have not been funded
THEN
where AUReceived<ProjectGoal
end --end the case
end -- end the proc
答案 0 :(得分:1)
WHERE关键字只能出现一次,并且出现在FROM子句之后。
SELECT *
FROM Stats.FundedProjectsToday
WHERE CASE
WHEN @QueryType = 1 -- Projects that reached their goal
THEN AUReceived >= ProjectGoal
WHEN @QueryType = 2 -- Projects that have not been funded
THEN AUReceived < ProjectGoal
END
可选地
SELECT *
FROM Stats.FundedProjectsToday
WHERE CASE @QueryType
WHEN 1 -- Projects that reached their goal
THEN AUReceived >= ProjectGoal
WHEN 2 -- Projects that have not been funded
THEN AUReceived < ProjectGoal
END
可能会早点写出
SELECT *
FROM Stats.FundedProjectsToday
WHERE (@QueryType = 1 AND AUReceived >= ProjectGoal)
OR (@QueryType = 2 AND AUReceived < ProjectGoal)
或
SELECT *
FROM Stats.FundedProjectsToday
WHERE @QueryType = 1
AND AUReceived >= ProjectGoal
UNION ALL
SELECT *
FROM Stats.FundedProjectsToday
WHERE @QueryType = 2
AND AUReceived < ProjectGoal
答案 1 :(得分:1)
对每个@QueryType
值使用互斥条件:
select *
from Stats.FundedProjectsToday
where (@QueryType = 1 and AUReceived >= ProjectGoal)
or (@QueryType = 2 and AUReceived < ProjectGoal)
顺便说一下,greater or equal operator写为>=
,而不是=>
。