【发布时间】:2010-05-07 12:10:26
【问题描述】:
继我的上一个问题Sql Server query performance 之后,发现我在搜索查询中允许可选参数的方法不是最佳的,有没有人有关于如何处理这个问题的指南?
例如,假设我有一个应用程序表、一个客户表和一个联系人详细信息表,并且我想创建一个 SP,它允许搜索姓氏、家庭电话、手机和应用程序 ID 的部分、无或全部,我可以使用类似下面的东西:
select *
from application a inner join customer c on a.customerid = a.id
left join contact hp on (c.id = hp.customerid and hp.contacttype = 'homephone')
left join contact mob on (c.id = mob.customerid and mob.contacttype = 'mobile')
where (a.ID = @ID or @ID is null)
and (c.Surname = @Surname or @Surname is null)
and (HP.phonenumber = @Homphone or @Homephone is null)
and (MOB.phonenumber = @Mobile or @Mobile is null)
上面使用的模式不是真实的,我不会在现实世界的场景中使用 select *,它是我感兴趣的 where 子句的构造。有没有更好的方法,动态 sql 或一种可以实现相同结果的替代方法,而不需要许多嵌套条件。一些 SP 可能有 10 - 15 条以这种方式使用的标准
【问题讨论】:
标签: sql-server tsql