Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

sql

sql-server

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)

enter link description here

Can someone help me figure this out?

like image 819
LearningAsIGo Avatar asked Feb 29 '16 18:02

LearningAsIGo


2 Answers

Use the LIKE operator with a JOIN.

SELECT A.*, B.*
FROM A
INNER JOIN B
ON A.Value LIKE CONCAT('%', B.IssueID, '%') 
like image 92
Chendur Avatar answered Sep 19 '22 22:09

Chendur


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.

like image 35
LearningAsIGo Avatar answered Sep 20 '22 22:09

LearningAsIGo