好的,我对此进行了广泛的研究,并尝试了许多技术,但都无济于事。
我有一个名字列表,我有一份地点列表。某些位置包含完整的名称字符串。
我只想提取其中某个位置包含名称的位置,并且我不想从%Names%的硬编码列表中进行检查,需要可扩展。我正在处理的内容如下(我不会每次都检查现有的临时表,这不是真正的需要)
所有的查询都是单独进行的,除了最后一个我最终尝试合并的查询
IF OBJECT_ID('tempdb..#ProviderList') IS NOT NULL
DROP TABLE #ProviderList
SELECT distinct
Station
,StaffName --first and last concatenated
,lastName
,ProviderID
--,[ProviderRole]
INTO #ProviderList
FROM --Omited--
Where PrimaryProviderSID in (Select distinct
PrimaryProviderSID
----
Where PrimaryPosition not like '%zz%'
AND PrimaryProviderID > 0)
AND [TerminationDate] is null
AND (InactivationDate is null)
Select LastName
INTO #LastName
from #ProviderList
/* Failed experiment
Declare @Names as Table(Name varchar(max))
Insert Into @Names Select LastName
from #ProviderList
--Select* From @Names
Failed experiment
*/
SELECT distinct [Many fields...],
LocationName
Into #LocationName
FROM ------
Where LocationName not like '%z%'
AND ---filtering criteria to make my list
---------------
我想从#LocationName中选择Everyting,但只选择名称列表中包含ANY记录的记录,它们将只包含一个或不包含
Select *
From #LocationName
Where #LastName in (LocationName)?
Where '%' + LastName + '%' ? --tried concatenation, i want a fuzzy search
Where #LocationName contains(LocationName, #LastName)? ---i know syntax is wrong but this has not proven to be the correct technique anyway
Where Exists(Select LastName from #LastName) --made no change but Not Exists returned nothing...
----------同事刚给我带来这个:
select lastname
from #LastName
Where charindex(LastName,
(SELECT STUFF((SELECT ',' + LocationName
FROM #LocationName
FOR XML PATH('')) ,1,1,'') AS Txt )
)>1
------但这只会给我们一个包含在LocationName字段中的名称列表,我们还想提取Location Name
我知道这是一个很长的过程,但我希望我相对清楚需要做什么,至少如果不是我如何做的话
我觉得我想制作一个数组,并分别比较每个Name值,看看它是否包含在LocationName中,如果是,则将其添加到新列表中。这将是理想的
尝试一下。。。
CREATE TABLE #NAMES (NAME VARCHAR(100))
CREATE TABLE #LOCATIONS (LOCATIONNAME VARCHAR(100))
INSERT INTO #NAMES
SELECT 'DAVE' UNION
SELECT 'BOB' UNION
SELECT 'JIMMY'
INSERT INTO #LOCATIONS
SELECT 'TODDS BOAT' UNION
SELECT 'MARYS HOUSE' UNION
SELECT 'DAVES HOTTUB' UNION
SELECT 'JIMMYS CRICKEY CLUB'
SELECT L.*
FROM #LOCATIONS L
CROSS APPLY #NAMES N
WHERE CHARINDEX(N.NAME, L.LOCATIONNAME)>0
也许这确实值得单独回答,而不仅仅是对JiggsJedi的评论。
它也可以使用相关的子查询来完成。此示例数据的执行计划在任何方面都是相同的。
使用JiggsJedi的示例数据。
SELECT L.*
FROM #LOCATIONS L
WHERE EXISTS (SELECT 1
FROM #NAMES N
WHERE CHARINDEX(N.NAME, L.LOCATIONNAME) > 0)