1

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

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',在开头为 ',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

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

4

3 回答 3

0

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

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

然后去掉双逗号:

SET @TagId = REPLACE(@TagId, ',' , ',')
于 2013-02-04T05:52:55.467 回答
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

于 2013-02-04T05:47:53.823 回答
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
于 2013-02-04T06:09:25.260 回答