SQL语句过滤结果

时间:2010-10-11 03:51:18

标签: sql sql-server

我需要根据3个条件过滤SQL查询结果:
1.位置
2.医生姓名
3.专业名称

如果所有3个条件都不为空,则下面是sql查询:

if (location != "" && doctor!="" && specialty!="")

select Location, ...
from clinicdoctors
where Location = @Location and DoctorName = @DoctorName and SpecialtyName = @SpecialtyName

}

如果只有位置为空,

if (location == "" && doctor!="" && specialty!="")
select Location, ...
from clinicdoctors
where Location is not null and DoctorName = @DoctorName and SpecialtyName = @SpecialtyName

...

如果我想检查所有条件,我需要写8个if语句。 在这种情况下,我该怎么做才能简化代码?

2 个答案:

答案 0 :(得分:2)

select Location, ...
from clinicdoctors
where 
 ISNULL(@Location,Location) = Location
 and ISNULL(@DoctorName,DoctorName) = DoctorName
 and ISNULL(@SpecialtyName,SpecialtyName) = SpecialtyName

答案 1 :(得分:0)

我认为在代码中执行此操作比使用sql更好。由于查询是如此不同,所以没有任何解决方法,但简单的方法是:

$loc_where = empty($loc) ? 'Location IS NOT NULL' : "Location = $loc";
$doc_where = empty($doc) ? 'AND DoctorName IS NOT NULL' : "AND DoctorName = $doc";
$spec_where = empty($spec) ? 'AND SpecialtyName IS NOT NULL' : "AND SpecialtyName = $spec";

query ... WHERE $loc_where $doc_where $spec_where