如何替换部分字符串?

How to substitute a partial string?

提前感谢您的帮助。 我想从 select 查询中删除部分字符串,其中有图例“ProcessError : Lens”,后跟 12 个数字,并将这 12 个数字替换为破折号。 我正在添加当前查询结果的结果:

          Error Description
 ProcessError : Lens 000300084502 is defect/scrap lens! 
 ProcessError : 20007  rejected 
 ProcessError : Lens 046000085174 is defect/scrap lens! 
 ProcessError : Lens 011900085176 is defect/scrap lens! 
 ProcessError : Lens 001200085188 is defect/scrap lens! 
 ProcessError : 20006  operation canceled 
 ProcessError : Lens 000300085787 is defect/scrap lens! 

谢谢,祝周末愉快。

假设每条记录不超过一个键字符串,您可以将 patindex() 与 stuff()

一起使用

例子

Declare @YourTable Table ([Error Description] varchar(150))
Insert Into @YourTable Values 
 ('ProcessError : Lens 000300084502 is defect/scrap lens!')
,('ProcessError : 20007')
,('ProcessError : Lens 046000085174 is defect/scrap lens!')
,('ProcessError : Lens 011900085176 is defect/scrap lens!')
,('ProcessError : Lens 001200085188 is defect/scrap lens!')
,('ProcessError : 20006')
,('ProcessError : Lens 000300085787 is defect/scrap lens!')
 
Select *
      ,NewVal = IsNull(stuff([Error Description]
                       ,patindex('%Lens [0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9]%', [Error Description])
                       ,17
                       ,'Lens ------------'
                 ),[Error Description])
 from @YourTable

Returns

Error Description                                       NewVal
ProcessError : Lens 000300084502 is defect/scrap lens!  ProcessError : Lens ------------ is defect/scrap lens!
ProcessError : 20007                                    ProcessError : 20007
ProcessError : Lens 046000085174 is defect/scrap lens!  ProcessError : Lens ------------ is defect/scrap lens!
ProcessError : Lens 011900085176 is defect/scrap lens!  ProcessError : Lens ------------ is defect/scrap lens!
ProcessError : Lens 001200085188 is defect/scrap lens!  ProcessError : Lens ------------ is defect/scrap lens!
ProcessError : 20006                                    ProcessError : 20006
ProcessError : Lens 000300085787 is defect/scrap lens!  ProcessError : Lens ------------ is defect/scrap lens!