我有接收性别价值的商店程序,可能是男性,女性或两者,我需要能够调整我的where子句,以便如果@gender值是'both',那么select应该返回男性和女性,但如果性别是男性或女性,则应选择@gender值。我试过下面的查询,它给出了错误的语法错误。
选择 FirstName,SecondName,Gender,race,Height,HeightUnit,Weight,WeightUnit,EmailAdd 来自志愿者
IF @gender = 'both'
BEGIN
WHERE Gender = 'male' or Gender ='female'
END ELSE BEGIN
WHERE Gender = @gender
END
答案 0 :(得分:2)
您不能使用if
来生成条件where
子句。相反,只需将逻辑放在查询中:
基于OP,您需要:
select FirstName, SecondName, Gender, race, Height, HeightUnit,
Weight, WeightUnit, EmailAdd
from volunteers
where @gender = 'both' and gender in ('male', 'female') or
gender = @gender;
或者,这可能就足够了:
select FirstName, SecondName, Gender, race, Height, HeightUnit,
Weight, WeightUnit, EmailAdd
from volunteers
where @gender = 'both' or
gender = @gender;
答案 1 :(得分:0)
好的如果我理解正确的话......试试这个:
select FirstName,SecondName,
CASE When @Gender = 'both' then 'Male, Female' else @Gender as Gender END
,race,Height,HeightUnit, Weight,WeightUnit,EmailAdd from volunteers
你可以准确地调整你想说的内容,但这就是想法
更新:根据评论,这是他正在使用的完整程序:
Create PROCEDURE spSelectUpdateTrial
@gender nvarchar(50),
@minage nvarchar(150),
@maxage nvarchar(150),
@country nvarchar(50),
@smoking nvarchar (50),
@smoke nvarchar(50),
@nct nvarchar(50) AS
select FirstName,
SecondName,
CASE
When @Gender = 'both'
then 'Male, Female'
else @Gender
END
as
Gender,
race,
Height,
HeightUnit,
Weight,
WeightUnit,
EmailAdd
from volunteers
注意我在else @gender