Basicaly, I want to select all items in tbl1 WHERE RANGE_DEP in tbl2 match RANGE in tbl1
tbl1
| ID | COD | PROCEDURE | RANGE |
| 1 | S1 | Procedure 1 | MM,ME,MG,TF,CH |
| 2 | S2 | Procedure 2 | ME,MG,CH |
| 3 | S3 | Procedure 3 | MM,MG,TF |
tbl2
| ID | DEPARTMENT | RANGE_DEP |
| 1 | D1 | MM,ME,CH |
| 2 | D2 | TF,CH |
I tried with
Declare @Range nvarchar(100) = SELECT RANGE FROM tbl1
SELECT * FROM tbl2 WHERE (SELECT RANGE_DEP FROM tbl1 WHERE DEPARTMENT = D1) IN (SELECT * FROM STRING_SPLIT(@Range, ','))
but I am pretty sure is not the corect way. Can you help, please?

Chetan SanghaniPosted Jul 13, 2024, 6:09 AM
Here is a step-by-step approach to solving this:
RANGEandRANGE_DEPcolumns into individual rows.Here's a SQL query that accomplishes this:
Explanation:
Splitting
tbl1:STRING_SPLITto split theRANGEcolumn intbl1and create a common table expression (CTE)SplitTbl1with each split value as a new row.Splitting
tbl2:STRING_SPLITto split theRANGE_DEPcolumn intbl2and create another CTESplitTbl2with each split value as a new row.Joining and Selecting:
tbl1,SplitTbl1, andSplitTbl2based on the split values. This ensures that we only select rows where the split values match.DISTINCTis used to ensure that we do not get duplicate rows in the final result.Notes:
TRIM(value)is used to remove any leading or trailing spaces around the split values.ORDER BYclause ensures that the result is sorted byID.This query will give you the rows from
tbl1where there is at least one matching value in theRANGEandRANGE_DEPcolumns.