简体   繁体   中英

SQL - If string in a column from one table contains string in column from joined table

I have two tables A and B. Table A has columns ID, Name and Value. Among other columns in table B, there is a column called IssueID. A.Value has values something like 'ForSymbol12345' and B.IssueID has values like '12345'. I am able to join these two tables on some ID columns in respective tables. However, I only want to select those rows where B.IssueID is present in A.Value value. In other words, B.IssueID is a substring of A.Value.

Can it be done in SQL? I tried using CONTAINS(string, 'value to search for') but apparently second parameter must be string and cannot be column name. I tried like

CONTAINS(A.Value, B.IssueID)

But it gives an error saying the second parameter is expected to be String, TEXT_LEX or Variable (a simplified example showing this below)

在此输入链接描述

Can someone help me figure this out?

Use the LIKE operator with a JOIN .

SELECT A.*, B.*
FROM A
INNER JOIN B
ON A.Value LIKE CONCAT('%', B.IssueID, '%') 

CONCAT option mentioned below by evil333 could have worked but I am using SSMS 2008 and CONCAT was introduced in SSMS 2012. So, I found a work around on that here

https://stackoverflow.com/a/21702750/3482656

You can do something like

A.value like '%' + cast(B.IssueID as varchar) + '%'

I hope this helps.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM