我想从以下字符串中删除给定值(例如1
),而无需拆分或使用XML功能。
/* input: */ @ObjectValue = '1,121,4,5,1,111,131,1'
/* output: */ '121,4,5,111,131'
答案 0 :(得分:1)
我认为最简单的方法是:
SELECT TRIM(',' from REPLACE(',' + @ObjectValue + ',', ',1,', ','))
TRIM()
在旧版本的SQL Server中不可用。一种方法是用空格替换逗号并使用可用的修剪函数:
SELECT REPLACE(LTRIM(RTRIM(REPLACE(REPLACE(',' + @ObjectValue + ',', ',1,', ','), ',', ' '))), ' ', ','),
答案 1 :(得分:1)
您需要将列表中的定界符加倍,以使1,1,1
变成,1,,1,,1,
。然后替换所有,1,
并随后进行清理:
SELECT ObjectValue, REPLACE(
LTRIM(RTRIM(
REPLACE(' ' + REPLACE(ObjectValue, ',', ' ') + ' ', ' 1 ', '')
)), ' ', ','
)
FROM (VALUES
('1'),
('1,1'),
('1,1,1'),
('0,1,0'),
('0,1,1,0'),
('0,1,1,1,0'),
('0,1,0,1,0'),
('1,0,0,1,0,0,1,1,0,1,0,1,1,1,1,1,0,1,0,0,1,1,0,1,0,1,0,1,0,1')
) AS v(ObjectValue)
答案 2 :(得分:0)
-- SSMS 2017
DECLARE @ObjectValue VARCHAR(100) = '1,121,4,5,1,111,131,1'
SELECT TRIM(',' FROM REPLACE(REPLACE(',' + @ObjectValue + ',', ',1,', ','),',1,', ','))
-- SSMS 2016 or earlier
DECLARE @Replacetxt VARCHAR(MAX)
SET @ObjectValue=REPLACE(REPLACE(','+@ObjectValue+',', ',1,', ','), ',1,', ',') --Replace ',1,' with ','
SET @Replacetxt=REVERSE(SUBSTRING(@ObjectValue, PATINDEX('%[^,]%', @ObjectValue), LEN(@ObjectValue))) -- Remove comma from starting and reverse string
SELECT REVERSE(SUBSTRING(@Replacetxt, PATINDEX('%[^,]%', @Replacetxt), LEN(@ObjectValue))) -- Remove comma from ending and reverse string