2017-10-11 87 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 | 
+------------------+ 

結論雖然這個解決方案工作正常它在性能和無效的逗號方面自身的風險(, )在表格行中。那些需要處理基於數據是如何存儲