SQL Server中以逗号分隔的列值匹配

时间:2017-10-11 05:26:41

标签: sql sql-server

在我的SQL Server表中,我有一个列Specialities,其值存储如下:

4' Tarps, 6' Tarps, 8' Tarps, Coil Racks, Edge Protectors, TWIC Card

即。值以逗号分隔的方式存储。

我想获取LIKE运算符中的列或该列中值匹配的任何其他运算符。

这就是我正在尝试的:

DECLARE @EquipmentServiceType nvarchar(max)

SET @EquipmentServiceType = '|Coil Racks|Hazmat|TWIC Card';
SET @EquipmentServiceType = REPLACE(@EquipmentServiceType,'''','')
SET @EquipmentServiceType = REPLACE(@EquipmentServiceType,'|',''',''')

select Specialities 
from CarrierData 
where Specialities like '%' + ''',''Coil Racks'',''Hazmat'',''TWIC Card''' + '%' 
    or Specialities like ',%' + ''',''Coil Racks'',''Hazmat'',''TWIC Card''' + ',%'

如何匹配SQL Server中的comma separated列?

这是表格图片: the table column is shown here

1 个答案:

答案 0 :(得分:0)

您应尝试更改数据库架构。

其他选项 - 您可以将CSV转换为表格,示例查询如下

DECLARE @strString VARCHAR(max)

SET @strString = '4'' Tarps, 6'' Tarps, 8'' Tarps, Coil Racks, Edge Protectors, TWIC Card'

DECLARE @x XML

SELECT
    @x = CAST('<Specialities><node>' +
     REPLACE(@strString, ',', '</node></Specialities><Specialities><node>') 
     + '</node></Specialities>' AS XML)

SELECT
    *
FROM (SELECT
        t.c.value('.', 'varchar(max)') AS Specialities
    FROM @x.nodes('//Specialities ') AS t (c)) AS final

--to declare WHERE Condition as needed, Uncomment the below  line

--WHERE final.Specialities LIKE '%Tarps%'

最终结果如下所示

+--------------+
| Specialities |
+--------------+
| 4' Tarps     |
|  6' Tarps    |
|  8' Tarps    |
+--------------+

修改

要搜索整个表行和列 - 下面是使用 COALESCE

在SQL语法中的更新
DECLARE @strString VARCHAR(max)

--SET @strString = '4'' Tarps, 6'' Tarps, 8'' Tarps, Coil Racks, Edge Protectors, TWIC Card'
--GETTING @strString directly from the table
-- Assuming the column name is Specialities

SELECT
    @strString = COALESCE(@strString + ',', '') + Specialities
FROM <WriteYourTableNameHere>

DECLARE @x XML

SELECT
    @x = CAST('<Specialities><node>' +
     REPLACE(@strString, ',', '</node></Specialities><Specialities><node>') 
     + '</node></Specialities>' AS XML)

SELECT
    *
FROM (SELECT
        t.c.value('.', 'varchar(max)') AS Specialities
    FROM @x.nodes('//Specialities ') AS t (c)) AS final

--to declare WHERE Condition as needed, Uncomment the below  line

--WHERE final.Specialities LIKE '%%'

这将得到如下结果

+------------------+
|   Specialities   |
+------------------+
| 4' Tarps         |
|  6' Tarps        |
|  8' Tarps        |
|  Coil Racks      |
|  Edge Protectors |
|  TWIC Card       |
| Partials         |
| None             |
| Partials         |
|  TWIC Card       |
| 4' Tarps         |
|  6' Tarps        |
|  Edge Protectors |
+------------------+

结论虽然此解决方案运行良好,但在性能方面存在风险,表行中的逗号(,)无效。您需要根据数据的存储方式处理的那些