函数replace的使用

1.查询

使用replace进行查询替换。把结果中的某些字符替换为自己想要的字符或为空。(查询不影响总体结果)

select [],replace([],'要查询的字符''查询到的字符所要修改的结果') from [表名]

实例:

select citySta,replace(citySta,'站''') AS new_station from stations

stations表结果:

cityStanew_station
广州南站广州南

2.更新

语句解释:
把库中包含“站”的文字(字符)都删除,如原始数据为广州南站,删除后变为广州南。
(可以理解为:查询表中某个字段最后一个字符为站的数据,并把 站 替换为空字符串)

update [表名] set [] = replace([], '站', '') where [] like '%站'

实例:

update stations set citySta = replace(citySta,'站','') where citySta like '%站'

stations表结果:

citySta(原数据)citySta(更新后数据)
广州南站广州南
郑州东站郑州东
北京西站北京西

假如需要把列中存在的郑州、郑州南改为北京

  1. 先把郑州南变成北京。
  2. 再把郑州变为北京。
update stations set citys = replace(citys,'郑州南','北京') where citys like '%郑州南%'
update stations set citys = replace(citys,'郑州','北京') where citys like '%郑州%'

更多推荐

SQLserver:函数replace的使用