表上的动态 JOIN 条件
我想避免在 SQL 2008 中使用字符串连接来创建动态 SQL 查询。
如何高效地实现以下功能(如果有的话)?
表存储用户通过使用一个或多个值来搜索表来选择搜索数据库的各种条件。例如,他可以提供 SSN 或 DOB,或者同时提供 SSN 和 DOB。
因此,如果他给出多个值作为输入,那么查询需要查找匹配所有条件的记录。这需要我从下面显示的两个表创建查询,
我总是需要返回 personid,它可能来自 person 表或视图。
用户给出的搜索条件将存储在下面的“条件”表中
conditions
-------------
id,custid,dob,ssn,base
person
--------
id,firstname,ssn,dob
view
--------
id,personid,base
So, IF DOB is to be searched
SELECT p.personid from conditon c
INNER JOIN person p
ON p.dob=c.dob
WHERE c.condition=1
IF SSN and base is to be searched
SELECT v.personid from conditon c
INNER JOIN view v
ON c.base=v.base
INNER JOIN person p
ON p.ssn=c.ssn
WHERE c.condition=1
IF SSN,DOB and base is to be searched
SELECT v.personid from conditon c
INNER JOIN view v
ON c.base=v.base
INNER JOIN person p
ON p.ssn=c.ssn
AND
p.dob=c.dob
WHERE c.condition=1
I want to avoid string concatenation to create dynamic SQL query in SQL 2008.
How can I achieve the below functionality, if at all, efficiently ?
A table stores the various conditions a user had chosen to search DB by using one or more values to search tables from. For e.g. he can give SSN or DOB or both SSN and DOB.
So if he gives multiple values as input, then the query needs to find records matching ALL the criteria. This needs me to create queries from the below shown two tables
I always need to return personid, which may be from the person table, or the view.
Search conditions given by user will be stored in the 'conditions' table below
conditions
-------------
id,custid,dob,ssn,base
person
--------
id,firstname,ssn,dob
view
--------
id,personid,base
So, IF DOB is to be searched
SELECT p.personid from conditon c
INNER JOIN person p
ON p.dob=c.dob
WHERE c.condition=1
IF SSN and base is to be searched
SELECT v.personid from conditon c
INNER JOIN view v
ON c.base=v.base
INNER JOIN person p
ON p.ssn=c.ssn
WHERE c.condition=1
IF SSN,DOB and base is to be searched
SELECT v.personid from conditon c
INNER JOIN view v
ON c.base=v.base
INNER JOIN person p
ON p.ssn=c.ssn
AND
p.dob=c.dob
WHERE c.condition=1
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
将下面的模式与 IsNull() 或 Coalesce() 函数一起使用
,或者在连接条件中使用相同的模式
然后,如果提供了参数,则 ql 将根据参数值进行过滤或连接,如果未提供或为空,查询将忽略它(ColumnValue = ColumnVale 始终为 true(可空列除外)
编辑:向连接条件添加另一个谓词。因为,在您没有指定参数值的情况下,连接条件将始终为 true,并且,除非连接中存在其他谓词条件,否则您将有效地获得笛卡尔积......
Use the pattern below with IsNull() or Coalesce() function
or tyhe same pattern in a Join Condition
And then, if the parameter is supplied, the ql will filter or join based on the parameter value, if it not supplied or is null, the query will ignore it (ColumnValue = ColumnVale is always true (except for nullable columns)
EDITED: to add another predicate to Join Condition. because, in the case where you did not specifiy a parameter value, the join condition would always be true, and, unless some other predicate condition is in the join, you would effectively get a cartesian product...