从模式中删除字符串中的特定字符

时间:2018-05-27 08:16:38

标签: sql sql-server

向sql写入查询时出现问题。问题如下:有一个填充表格,其中包含FILE_NAME列,在此列中,有必要删除某些元素中的数字0。这个0总是在行中的相同位置。下面我附上数据截图,必须删除黄色字符。

problem

3 个答案:

答案 0 :(得分:1)

使用SUBSTRINGLEN函数作为下一个模式尝试此方法: -

Update tableName
Set columnName = substring(columnName , 0, 9) +
                 substring(columnName , 10, len(columnName ))
Where substring(columnName , 9, 1) = '0' 
And len(columnName ) > 15

<强>演示

Create table #Temp (Col1 varchar(20))
insert into #Temp values ('18_0231_0121_001') -- Remove the 0 in index #9
insert into #Temp values ('18_0231_0121_12') -- keep the 0 in index #9
insert into #Temp values ('18_0231_2121_001') -- there is no 0 in index #9, so keep it as it is

select * from #Temp

更新前的结果

18_0231_0121_001
18_0231_0121_12
18_0231_2121_001

将更新用作下一个

update #Temp 
set Col1 = substring(Col1, 0, 9) + substring(Col1, 10, len(Col1))
where substring(Col1, 9, 1) = '0' and len(Col1) > 15

select * from #Temp

更新后的结果

18_0231_121_001
18_0231_0121_12
18_0231_2121_001

答案 1 :(得分:0)

0始终在9索引上

在此索引中替换0,仅当第二个和第三个下划线之间有4个字符时

字符串必须采用下一格式:18_0000_000_000

Update myTable
Set FILE_NAME = substring(FILE_NAME, 1, 8) +    -- first 8 characters
                substring(FILE_NAME, 10, 1000)  -- character 10 to end of string
where
   -- four characters with a zero at position 9 followed by of three characters and an underscroe
   Col1 like '_______\_0___\____' escape '\' 

答案 2 :(得分:0)

使用stuff()功能更容易:

update tableName
    set columnName = stuff(columnName, 9, 1, '');
where substring(columnName , 9, 1) = '0' and len(columnName ) > 15;