Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Compare comma delimited strings in SQL

I have search requests that come in a CDL ("1,2,3,4"),("1,5"). I need to compare that to another CDL and return back all records that have a match. The kicker is the position of each number isn't always the same.

I've got something almost working except for instances where I'm trying to match ("2,5") to ("2,4,5"). Obviously the strings aren't equal but I need to return that match, because it has all the values in the first CDL.

My SQL Fiddle should make it fairly clear...

Any help would be much appreciated.

Oh and I saw this one is similar, but that seems a little drastic and over my head but I'll see if I can try to understand it.

Edit
So I just did a replace to change ("2,5") to ("%2%5%") and changed the were to use LIKE. From what I can initially tell it seems to be working.. SQL Fiddle Any reason I shouldn't do this or maybe I'm crazy and it doesn't work at all?

like image 740
EmptyChair Avatar asked Mar 28 '13 22:03

EmptyChair


People also ask

How do you compare strings in SQL?

SELECT STRCMP(argument1, argument2); Here, argument1 and argument2 are string type data values which we want to compare. The syntax for using LIKE wildcard for comparing strings in SQL is as follows : SELECT column_name1, column_name2,...

How do I match two rows in SQL?

Example 1: Comparing rows of the same table. In the example, we are comparing the immediate rows to calculate the sales made on a day by comparing the amounts of two consecutive days. Syntax for inner join : SELECT column_name(s) FROM table1 t1 INNER JOIN table1 t2 on t1. column1 = t2.

Can we compare two columns in SQL?

In SQL, problems require us to compare two columns for equality to achieve certain desired results. This can be achieved through the use of the =(equal to) operator between 2 columns names to be compared.


1 Answers

Just one step further, get closer to your answer.
SQL FIDDLE DEMO


SELECT P.* 
FROM Product P
CROSS APPLY(
  SELECT *
  FROM ShelfSearch SS
  WHERE Patindex(char(37)+replace(ss.shelflist, ',',char(37))+char(37),p.shelflist) > 0
)Shelfs
like image 65
ljh Avatar answered Oct 19 '22 12:10

ljh