我的Bus
表格存在问题,其中包含:
Bus_no(int)
Bus_Route(Varchar)
Bus_Stop(varchar)
我的Bus_Stop
列包含以逗号分隔的字符串停止,如下所示:
'Apsara,Shahadara,Shakarpur,Mother Dairy,Badarpur,'
我需要在Shakarpur
中搜索SQL Server
这样的特定单词而不使用逗号。
答案 0 :(得分:0)
如果你想要匹配,那么检查并选择const:
select BusNo,
BusRoute,
case when BusStop = 'Shakarpur' or
BusStop like 'Shakarpur,%' or
BusStop like '%,Shakarpur,%' or
BusStop like '%,Shakarpur'
then 'Shakarpur' end as BusStop
from Bus
如果您有参数:
select BusNo,
BusRoute,
case when BusStop = @p or
BusStop like @p + ',%' or
BusStop like '%,' + @p + ',%' or
BusStop like '%,' + @p
then @p end as BusStop
from Bus
修改强>
以下是零件匹配的解决方案:
DECLARE @t TABLE
(
Bus_no INT ,
Bus_Route VARCHAR(20) ,
Bus_Stop VARCHAR(200)
)
INSERT INTO @t
VALUES ( 1, '1', 'Apsara,Shahadara,Shakarpur,Mother Dairy,Badarpur' ),
( 2, '2', 'Amsterdam,Brussels,Bruges,Brussels,London,Liverpool' ),
( 3, '3', 'k,k,k' );
;WITH cte AS(SELECT Bus_no ,
Bus_Route ,
Split.a.value('.', 'VARCHAR(100)') Bus_Stop
FROM ( SELECT Bus_no ,
Bus_Route ,
CAST ('<M>' + REPLACE(Bus_Stop, ',', '</M><M>') + '</M>' AS XML) AS Data
FROM @t
) AS t
CROSS APPLY Data.nodes('/M') AS Split ( a ))
SELECT Bus_no,
Bus_Route,
STUFF((Select ',' + c2.Bus_Stop
From cte c2
Where c1.Bus_no = c2.Bus_no AND Bus_Stop LIKE '%s%'
For XML PATH ('')), 1, 1, '') Bus_Stop
FROM cte c1
WHERE Bus_Stop LIKE '%s%'
GROUP BY Bus_no, Bus_Route
输出:
Bus_no Bus_Route Bus_Stop
1 1 Apsara,Shahadara,Shakarpur
2 2 Amsterdam,Brussels,Bruges,Brussels