我们可以在WHERE子句中使用STRING_SPLIT()拆分字符串以与多个值进行比较吗?



我有两个表。我们可以在WHERE子句中使用STRING_SPLIT()来分割字符串以与多个值进行比较吗?我的问题会更清楚。

Table1

| columnA | columnB |
| ------- | ------- |
|    1    |  A,B,C  |
|    2    |  A,B    |
|    3    |  B,C    |

|  value  |  
| ------- |
|    A    |
|    B    |
|    C    |

我尝试了下面的查询,但它没有工作。

select * from Table1 where STRING_SPLIT(columnB,',') IN (select value from Table2)

感谢

您可以使用join:

select t1.*
from Table1 t1 cross apply
string_split(t1.b, ',') s join
table2 t2
on t2.value = s.value;

或子查询:

select t1.*
from table1 t1
where exists (select 1
from string_split(t1.b, ',') s join
table2 t2
on t2.value = s.value;
);

但是你真的应该修复你的数据模型,这样你就不会在一个字符串列中存储多个值。

这可能适合您。

(不使用STRING_SPLIT功能)

select * from Table1 
inner join Table2 on ',' + Table1.ColumnB + ',' like '%,' + Table2.Value + ',%' 

不确定性能。你需要自己计时。