将所有数字替换为三位数或更多位数

时间:2017-05-05 18:07:54

标签: sql replace sql-server-2016

我有一个字段说"关键字"其中包含随机数字字符串,我希望从任何超过3位数字的数字字符串中清除该字段。

enter image description here

我已经搜索并且知道更换通配符是不可能的。知道我怎么能这样做吗?

2 个答案:

答案 0 :(得分:0)

自2016年以来,您可以将 String_Split() Try_Convert()

一起使用

示例

Declare @YourTable table (idproduct int,searchkeywords varchar(500))
Insert Into @YourTable values
(109070,'stands & cabinets kantec ams300 1010055 43212002 03906786808 7503 ktkams ltk ams 300')

Select A.idproduct
      ,NewString = B.S
 From  @YourTable A
 Cross Apply (
              Select S = Stuff((Select ' ' +Value
               From (Select Value,Seq=Row_Number() over (Order by (select null))
                       From String_Split(A.searchkeywords,' ')
                    ) B1
              Where (try_convert(float,Value) is null)
                 or (try_convert(float,Value) is not null and len(Value)<=3)
              Order by Seq
              For XML Path ('')),1,1,'') 
            ) B

<强>返回

idproduct   NewString
109070      stands & cabinets kantec ams300 ktkams ltk ams 300

如果您对结果感到满意,可以应用如下更新:

Update A Set searchkeywords = B.S
 From  @YourTable A
 Cross Apply (
              Select S = Stuff((Select ' ' +Value
               From (Select Value,Seq=Row_Number() over (Order by (select null))
                       From String_Split(A.searchkeywords,' ')
                    ) B1
              Where (try_convert(float,Value) is null)
                 or (try_convert(float,Value) is not null and len(Value)<=3)
              Order by Seq
              For XML Path ('')),1,1,'') 
            ) B

答案 1 :(得分:0)

这是一个开始的好地方

假设您有一个名为&#34; test_test&#34;:

的表
results.insertId

使用这样的值:

create table dbo.test_test (thisStuff varchar(100));

您可以使用insert into test_test values ('Hello123 this is 12 a test 22983o398r57298298347238'); 进行有限的模式匹配:

patindex()

转换此值:

select substring(thisStuff,
                 1,
                 patindex('%[0-9][0-9][0-9]%',thisStuff)-1) + 
       substring(thisStuff,
                 patindex('%[0-9][0-9][0-9]%',thisStuff)+3,
                 len(thisStuff)) 
from test_test

进入此值:

Hello123 this is 12 a test 22983o398r57298298347238

在更新表单中,它看起来像这样:

Hello this is 12 a test 22983o398r57298298347238

当反复运行时,会为您提供渐进的值:

update test_test set thisStuff =
   substring(thisStuff,
             1,
             patindex('%[0-9][0-9][0-9]%',thisStuff)-1) + 
   substring(thisStuff,
             patindex('%[0-9][0-9][0-9]%',thisStuff)+3,
             len(thisStuff));

出错之前

Hello this is 12 a test 83o398r57298298347238
Hello this is 12 a test 83or57298298347238
Hello this is 12 a test 83or98298347238
Hello this is 12 a test 83or98347238
Hello this is 12 a test 83or47238
Hello this is 12 a test 83or38