Search SQL Server string for values from another table

爱⌒轻易说出口 提交于 2020-01-17 13:27:34

问题


I have a table with column name that has random characters before and after the name ie:

Table A:

  Name
  -----------------
  asd4345JONlkj345
  .;lidDavidlksd$

and I have another table in same DB that has the names ie:

Table B:

 Name
 ------
 David
 Jon

This goes on like this for 30k rows or I'd just hardcode something really quick. I want to search each string in Table A 'Name' column for each value from Table B, and if found return the name in a new column.

I have a feeling this will be a UDF, which is fine, I'm just unsure how to use patindex in this scenario, or if that is even the right approach.


回答1:


You only need the LIKE operator for this:

select * 
from TableA
inner join TableB on TableA.Name like '%' + TableB.Name + '%'



回答2:


  select B.Name, A.Name from tableA A inner join join tableB B
  on rtrim(ltrim(B.Name)) like '%' + rtrim(ltrim(A.Name)) + '%'


来源:https://stackoverflow.com/questions/40368799/search-sql-server-string-for-values-from-another-table

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!