MySQL的replace()函數

今天在工做的過程當中碰到一個問題,要把數據庫中某個列的全部值中含有"shop.xxxx.net"的字符更換成"www.nowamagic.net",原本能夠寫個腳本,把全部的值都取出再用php進行處理,可是那樣就效率很是低了,想到看試下能不能直接在MySQL中用SQL語句直接來處理,通過一番搜索,終於找到解決方案,其實最重要的是mysql的replace函數,關於這個函數的介紹,我在MySQL手冊中是沒看懂,不過能實現我想要的功能就行。 php

下面就是對這個函數的簡要介紹以及範例。 mysql

好比你要將 表 tb1裏面的 f1字段的abc替換爲def: sql

1 UPDATE tb1 SET f1=REPLACE(f1, 'abc', 'def');
2 REPLACE(str,from_str,to_str)

在字符串 str 中全部出現的字符串 from_str 均被 to_str替換,而後返回這個字符串: 數據庫

1 mysql>   SELECT   REPLACE('www.mysql.com',   'w',   'Ww');
2 ->   'WwWwWw.mysql.com'

這個函數是多字節安全的。 安全

示例: app

1 UPDATE  `dede_addonarticle`  SET body =  REPLACE ( body,'</td>'," );
2 UPDATE  `dede_addonarticle`  SET body =  REPLACE ( body,'</tr>'," );
3 UPDATE  `dede_addonarticle`  SET body =  REPLACE ( body,'<tr>'," );
4 UPDATE  `dede_archives`  SET title=  REPLACE ( title,'簡明現代魔法 – '," );
5 UPDATE  `dede_addonarticle`  SET body =  REPLACE ( body,'../../../../../../','http://special.dayoo.com/meal/' );

mysql replace

用法1.replace intoreplace into table (id,name) values('1','aa'),('2','bb') 函數

此語句的做用是向表table中插入兩條記錄。 spa

2.replace(object, search,replace) .net

把object中出現search的所有替換爲replaceselect replace('www.163.com','w','Ww')—>WwW wWw.163.com orm

例:把表table中的name字段中的 aa替換爲bbupdate table set name=replace(name,'aa','bb')

Sql Server 中 text或ntext 字段內容替換

剛開始,Update AA 表 Set xx字段=Replace(xx字段,"要替換的","特定串") ,出現錯誤:函數 replace 的參數 1 的數據類型 ntext 無效。Update article set heading=Replace(convert(nvarchar(4000),heading),'<script></script>','')

1 update 表名
2     set text類型字段名=replace(convert(varchar(8000),text類型字段名),'要替換的字符','替換成的值')

varchar和nvarchar類型是支持replace,因此若是你的text/ntext不超過8000/4000能夠先轉換成前面兩種類型再使用replace。

1 update 表名
2     set text類型字段名=replace(convert(varchar(8000),text類型字段名),'要替換的字符','替換成的值')
1 update 表名
2     set ntext類型字段名=replace(convert(nvarchar(4000),ntext類型字段名),'要替換的字符','替換成的值')

若是text/ntext超過8000/4000,看以下例子:

01 declare @pos  int
02     declare @len  int
03     declare @str nvarchar(4000)
04     declare @des nvarchar(4000)
05     declare @count  int
06    set @des ='<requested_amount+1>'--要替換成的值
07  
08    set @len=len(@des)
09    set @str= '<requested_amount>'--要替換的字符
10  
11  
12    set @count=0--統計次數.
13  
14  
15     WHILE 1=1
16    BEGIN
17        select @pos=patINDEX('%'+@des+'%',propxmldata) - 1
18        from 表名
19        where 條件
20  
21       IF @pos>=0
22       begin
23            DECLARE @ptrval binary(16)
24           SELECT @ptrval = TEXTPTR(字段名)
25           from 表名
26           where 條件
27            UPDATETEXT 表名.字段名 @ptrval @pos @len @str
28           set @count=@count+1
29        end
30       ELSE
31          break;
32    END
33  
34    select @count
相關文章
相關標籤/搜索