让我开始描述问题。有一个字段/列是多值的,不是原子的,据我了解,这违反了规范化规则。字段Constituent_list可以具有如下字符串:
Alumni Owned/Gift Source / Committee member / Donor / Donor Advised Funds / Foundation / Major donor / Trustee Gift Source - Org.
这些值以/分隔表示实体的特征。因此,它们可以是Donor,Trustee,具有唯一值数量的表最多可以包含45个值。因此,一个实体可能具有45个表征它的值。
我想用该列查询表。该表具有数千行,因此,如果查询选择了5、10、20个可能的特征,则该查询必须为任何给定的行处理n个可能的值,以查看其是否满足查询条件。但是,如果已经选择了该行,那么为什么要测试另一个值(如果该行已成为记录集的一部分)呢?下面的代码显示了一个选择,但是它使用的是我选择的多值字符串,而不是查找表中具有45个值作为单独行的单个值。
DECLARE @P_Constituent AS nvarchar(1000)
SET @P_Constituent = 'Alumni Owned/Gift Source / Committee member / Donor / Donor Advised Funds / Foundation / Major donor / Trustee Gift Source - Org.'
SELECT *
FROM [Entity]
WHERE Constituency_List IN (@P_Constituent)
这是表的外观,其中包含将在查询中使用的值:
Constituency
Alumni Owned/Gift Source
Alumnus
Associated Prospect
Board member
Committee member
Corp. Foundation
Corporation
Donor
Donor Advised Funds
Estate of
Event registrant
Faculty/Staff
Family Foundation
Fellow/Post Doc
Former Employee
Former Parent
Former Student
Foundation
Friend
Fundraiser
Governmental Entity
Group/Trade Union
Headquarters
Honorary Alumnus
Institution/Educ.
Law Firm
Living Trust
Loyal donor
Major donor
Non-grad Alumnus
NYU Affiliate
Organization/Vol Hth
Other
Parent
Parent Source - Org.
Patient
Prospect
Religious
Staff
Student
Trust
Trustee Gift Source - Org.
Trustee Gift Source - Person
Vendor
因此,最有效的方法是使用上面的表使用此多值列查询表的最佳方法是什么?
DECLARE @P_Constituent AS nvarchar(1000);
SET @P_Constituent = 'Alumni Owned/Gift Source / Committee member / Donor / Donor Advised Funds / Foundation / Major donor / Trustee Gift Source - Org.';
--Try it out
--SELECT TRIM(value) AS value FROM STRING_SPLIT(@P_Constituent,'/');
SELECT *
FROM [Entity]
WHERE Constituency_List IN (
SELECT TRIM(value) AS value FROM STRING_SPLIT(@P_Constituent,'/')
)
请注意,STRING_SPLIT
可从SQL Sever 2016版及更高版本获得。
请根据需要阅读有关STRING_SPLIT的更多信息。