我有2个表格,如下所示:
人
-----------------------------------------------
Id | Name | Age | Gender | Address | Nationality
------------------------------------------------
1 | Ram | 30 | Male | Hyderabad| Indian <br/>
2 | Raj | 30 | Male | Delhi | Indian <br/>
查找
------------------------------------------
LookupId | Key | Value
------------------------------------------
1 | Age | 30
2 | Gender | Male
3 | Address | Chennai
4 | Nationality | Indian
5 | Age | 24
6 | Gender | Male
7 | Address | Hyderabad
8 | Nationality | Indian
9 | Age | 30
10 | Gender | Male
11 | Address | Delhi
12 | Nationality | Indian
13 | Age | 34
14 | Gender | Female
15 | Address | Mumbai
16 | Nationality | Indian
基于以上数据,当用户选择多个查找时,从Persons表中获取Person信息的建议或最佳方法是什么。
例如:
对于lookupIds 1,2,8,应返回人员1和2
对于lookupIds 1,2,7,8将返回人ID 1
对于lookupIds 5,6,7,8,不会返回任何记录,依此类推。
答案 0 :(得分:0)
您可以使用以下查询根据所选值构建动态sql语句。此查询将为您提供必须针对人员表
运行的实际查询WITH STMT
AS
(
select id,
REPLACE(stuff((
select ';'+ key + '='''+value+''''
from lookups
WHERE ID IN (1,2,7,8)
for xml path('')
),1,1,''),';',' AND ') COND
from lookups
WHERE ID IN (1,2,7,8)
)
SELECT TOP 1 ' SELECT * FROM persons WHERE '+ COND
FROM STMT