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

时间:2015-01-11 10:16:43

标签: sql sql-server replace

我有来自特定表格的记录,其中包含字段:phone1phone2

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

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

4 个答案:

答案 0 :(得分: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

答案 1 :(得分: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

答案 2 :(得分:0)

您必须实施两个部分:

  1. 检查电话号码是否以特定顺序开头 (WHERE phone LIKE '057%'
  2. 获取057之后的部分 与新的('053' + RIGHT(phone, LEN(phone) - 3)
  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 + '%')
    

答案 3 :(得分:0)

for sql server 2012使用东西

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