如何仅更改匹配条件的值的开头?

问题描述 投票:0回答:4

我有一个特定表的记录,其中包含字段:phone1phone2

如何在这些字段中将057的值更改为053,但只是值的开头?

例如:057-4353009应更改为053-4353009,但057-5405731应更改为053-5405731(此特定数字中的第二个057不应更改)。

sql sql-server replace
4个回答
0
投票

你必须实现两个部分:

  1. 检查电话号码是否以特定顺序开头(WHERE phone LIKE '057%'
  2. 获得057之后的部分并与新的部分连接('053' + RIGHT(phone, LEN(phone) - 3)

以下是执行此操作的示例查询:

UPDATE
  tbl
SET
  phone = '053' + RIGHT(phone, LEN(phone) - 3) -- Leaving the first 3 characters and use another one
WHERE
  phone LIKE '057%' -- Starts with 057

一般的解决方案是这样的:

DECLARE
    @SearchString NVARCHAR(MAX) = '057'
  , @ReplaceString NVARCHAR(MAX) = '053'

UPDATE
  tbl
SET
  phone = @ReplaceString + RIGHT(phone, LEN(phone) - LEN(@SearchString))
WHERE
  phone LIKE (@SearchString + '%')

0
投票

试试这个(适合我):

UPDATE       table1
SET                phone = table2.leftc + table2.rightc
FROM            table1 INNER JOIN
                     (select  '053' as leftc, RIGHT(phone ,Len(phone) - 3)as rightc, phone 
                        from table1
                        where  LEFT(phone, 3) = '057') AS table2 ON table1.phone = table2.phone

Working Demo Here


0
投票

对于sql server 2012使用的东西

update tbl
set phone_number=stuff(phone_number,1,3,'053')
WHERE
  phone_number LIKE '057%'

0
投票

你可以使用REPLACE

UPDATE tbl
SET phone = REPLACE(phone, '057-', '053-')

SQLFiddle

编辑:如果您不确定该数字是否具有xxx-xxxxxxx中的分隔符结构:

UPDATE tbl 
SET phone = '053' + SUBSTRING(phone, 4 , LEN(phone) - 1)
WHERE LEFT(phone, 3) = '057';

SQLFiddle

© www.soinside.com 2019 - 2024. All rights reserved.