我的列可以包含以下结果:
ER
ER,ER,ER
ER,ER,OR,OR
OR
OR,OR
OR,OR,OR,ER,ER
我正在寻找一种方法来将"ER,ER,ER,OR,OR"
之类的字符串替换为"ER,OR"
。无论ER
或OR
出现多少次,我只希望每次只显示一次。谢谢
答案 0 :(得分:1)
创建拆分功能(或在此站点上搜索数百种变体):
CREATE FUNCTION [dbo].[SplitStrings_XML]
(
@List NVARCHAR(MAX),
@Delimiter NVARCHAR(255)
)
RETURNS TABLE
WITH SCHEMABINDING
AS
RETURN
(
SELECT Item = y.i.value('(./text())[1]', 'nvarchar(4000)')
FROM
(
SELECT x = CONVERT(XML, '<i>'
+ REPLACE(@List, @Delimiter, '</i><i>') + '</i>').query('.')
) AS a
CROSS APPLY x.nodes('i') AS y(i)
);
GO
然后你可以这样做:
DECLARE @x TABLE(foo VARCHAR(32));
INSERT @x SELECT 'ER'
UNION ALL SELECT 'ER,ER,ER'
UNION ALL SELECT 'ER,ER,OR,OR'
UNION ALL SELECT 'OR'
UNION ALL SELECT 'OR,OR'
UNION ALL SELECT 'OR,OR,OR,ER,ER';
;WITH g AS
(
SELECT x.foo, s.Item
FROM @x AS x
CROSS APPLY dbo.SplitStrings_XML(x.foo, ',') AS s
GROUP BY x.foo, s.Item
)
SELECT original = x.foo, new = STUFF((SELECT ',' + Item FROM g
WHERE foo = x.foo GROUP BY Item
FOR XML PATH, TYPE).value('.[1]', 'nvarchar(max)'), 1, 1, '')
FROM @x AS x;
结果几乎完全符合您的要求,但不保留初始字符串的顺序:
original new
----------------- ----------
ER ER
ER,ER,ER ER
ER,ER,OR,OR ER,OR
OR OR
OR,OR OR
OR,OR,OR,ER,ER ER,OR
答案 1 :(得分:0)
快速而肮脏的方式就是这样......虽然它仅限于您在问题中提供的示例。从概念上讲,KM的问题评论中提供了更好的方法。
update mytable
set mycolumn =
case when (mycolumn like '%er%' and not mycolumn like '%or%') then 'ER'
when (mycolumn like '%or%' and not mycolumn like '%er%') then 'OR'
when (mycolumn like '%er%' and mycolumn like '%or%') then 'ER,OR' end