2017-10-11 127 views
1

以我SQL Server表我有与存储这样值的列Specialities在SQL Server逗号分隔列值匹配

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

+0

添加样本数据与预期的结果。 –

+5

将值保存为csv并不是一个好主意。重新设计你的数据库 – Jens

+0

我已经加入 – asasasaa

回答

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 | 
+--------------+ 

编辑

要搜索整个表格的行和列 - 下面是更新的SQL语法使用COALESCE

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 | 
+------------------+ 

结论虽然这个解决方案工作正常它在性能和无效的逗号方面自身的风险(, )在表格行中。那些需要处理基于数据是如何存储