SQL语句过滤结果
我需要根据3个条件过滤SQL查询结果:
1. 地点
2. 医生姓名
3. 专业名称
下面是 3 个条件都不为空时的 sql 查询:
if (location != "" && doctor!="" && specialty!="")
select Location, ...
from clinicdoctors
where Location = @Location and DoctorName = @DoctorName and SpecialtyName = @SpecialtyName
}
如果只有 location 为空,
if (location == "" && doctor!="" && specialty!="")
select Location, ...
from clinicdoctors
where Location is not null and DoctorName = @DoctorName and SpecialtyName = @SpecialtyName
...
如果我想检查所有条件,我需要编写 8 个 if 语句。 在这种情况下我应该做什么来简化代码?
I need to filter the SQL query result according to 3 conditions:
1. Location
2. Doctor Name
3. Specialty Name
Below is the sql query if all 3 conditions are not empty:
if (location != "" && doctor!="" && specialty!="")
select Location, ...
from clinicdoctors
where Location = @Location and DoctorName = @DoctorName and SpecialtyName = @SpecialtyName
}
if only location is empty,
if (location == "" && doctor!="" && specialty!="")
select Location, ...
from clinicdoctors
where Location is not null and DoctorName = @DoctorName and SpecialtyName = @SpecialtyName
...
If I wanna check all the conditions, I need to write eight if statements.
What should I do to simplify the code in this situation?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我认为在代码中执行此操作比像您所做的那样在 sql 中执行此操作更好。由于查询如此不同,实际上没有任何解决办法,但一种简洁的方法是:
I think it would be better to do this in the code than sql as you have done. Not really any way around it since the queries are so different, but a terse way to do it would be: