通过替换特定字符串来更新列值

时间:2013-02-04 05:42:12

标签: sql

我有一个列,它将数据保存在这样的行中:

Col1 '2118,2110,2114,2112',
Col2 '2110,2111,2112,2113,2114,2115,2117,2118,2119,2152,2153' and 
Col3 '2110,2111,2113,2114'. 

现在,当我运行删除命令删除2110时,我想从每列替换2110

我尝试的是(我正在为col1值执行此操作 - 我在字符串的开头和结尾添加一个逗号,以便它符合结果,即如果逗号在2110之后为'2110,'在start as',2110 '并从开始和结束',2110,')

DECLARE @TagId VARCHAR(MAX)
SET @TagId = '2118,2110,2114,2112'
print 'Select Tag ' + @TagId
SET @TagId = ',' + @TagId + ','
print 'Adding comma ' + @TagId
SET @TagId = REPLACE(@TagId,',2110,',',')
print 'Replace the string ' + @TagId
SET @TagId = SUBSTRING(@TagId,1,LEN(@TagId))
print 'Replace start comma ' + @TagId
SET @TagId = SUBSTRING(@TagId,0,LEN(@TagId) -1)
print 'Replace end comma' + @TagId
SELECT @TagId

现在的问题是它没有替换我在开始时添加的开头和结尾的逗号。请告诉我这里我做错了什么。

3 个答案:

答案 0 :(得分:0)

试试这个:

DECLARE @TagId VARCHAR(MAX)
SET @TagId = '2118,2110,2114,2112'
print 'Select Tag ' + @TagId
SET @TagId = ',' + @TagId + ','
print 'Adding comma ' + @TagId
SET @TagId = REPLACE(@TagId,',2110,',',')
print 'Replace the string ' + @TagId
SET @TagId = SUBSTRING(@TagId,2,LEN(@TagId))
print 'Replace start comma ' + @TagId
SET @TagId = SUBSTRING(@TagId,0,LEN(@TagId))
print 'Replace end cooma' + @TagId
SELECT @TagId

更多关于SUBSTRING

答案 1 :(得分:0)

为什么要在开头和结尾添加逗号? 当然你可以像这样替换:

DECLARE @TagId VARCHAR(MAX)
SET @TagId = '2118,2110,2114,2112'
SET @TagId = REPLACE(@TagId, '2110' , '')

然后删除双逗号:

SET @TagId = REPLACE(@TagId, ',' , ',')

答案 2 :(得分:0)

试试这个,

DECLARE @TagId VARCHAR(MAX)
SET @TagId = '2118,2110,2114,2112'
print 'Select Tag ' + @TagId
SET @TagId = ',' + @TagId + ','
print 'Adding comma ' + @TagId
SET @TagId = REPLACE(@TagId,',2110,',',')
print 'Replace the string ' + @TagId
SET @TagId = CASE WHEN LEN(@TagId) > 1 THEN SUBSTRING(@TagId,2,LEN(@TagId)) 
             ELSE @TagId END
print 'Replace start comma ' + @TagId
SET @TagId = SUBSTRING(@TagId,1,LEN(@TagId) -1)
print 'Replace end comma ' + @TagId
SELECT @TagId