我正在使用SQL Server,如何在SQL语句的ImageView
子句中使用CASE
语句?
我想重写这个查询:
where
使用select *
from Persons P
where P.Age = 20
and P.FamilyName in (select Name
from AnotherTable)
语句。我想要它第二个条件
case
仅当(P.FamilyName in ....)
为真时才执行。
这样的事情:
CheckFamilyName
SQL中的select *
from Persons P
where P.Age = 20
case when CheckFamilyName= true
then
and P.FamilyName in (
select Name
From AnotherTable)
else
end
语句如何工作?
答案 0 :(得分:4)
where P.Age = 20
and
(
not CheckFamilyName
or
P.FamilyName in (select Name From AnotherTable)
)
答案 1 :(得分:2)
接近1
select *
from Persons P
where 1=1
and P.Age = 20
and (
CheckFamilyName = 0
or P.FamilyName in (select Name From AnotherTable)
)
接近2
select *
from Persons P
where 1=1
and P.Age = 20
and CheckFamilyName = '0'
union all
select *
from Persons P
where 1=1
and P.Age = 20
and CheckFamilyName = '1'
and P.FamilyName in (select Name From AnotherTable)
答案 2 :(得分:0)
首先,您可以(也可能应该)使用第一个案例的联接:
selectionMode
应该注意的是,这个select语句只会给你带有该姓氏的结果。
所以当你添加新条件时
select *
from Persons P
join anothertable A on A.Name = P.FamilyName
where P.Age = 20
您只能获得CheckFamilyName为true的结果。
所以我们把它作为左连接。
select *
from Persons P
join anothertable A on A.Name = P.FamilyName and P.CheckFamilyName= true
where P.Age = 20
这将包括checkfamilyname为true但名称不存在的行 - 验证可以执行以下操作的行
select *
from Persons P
left join anothertable A on A.Name = P.FamilyName and CheckFamilyName= true
where P.Age = 20