#下面就是对这个函数的简要介绍以及范例。
#示例:
#比如你要将 表 tb1里面的 f1字段的abc替换为def:
1
|
UPDATE tb1 SET f1=REPLACE(f1,
'abc'
,
'def'
);
|
#函数的本用法:
REPLACE(目标字符串,搜索字符串,替换字符串);
#在字符串 str 中所有出现的字符串 from_str 均被 to_str替换,然后返回这个字符串:
1
2
3
4
|
REPLACE(str,from_str,to_str);
SELECT REPLACE(
'www.mysql.com'
,
'w'
,
'Ww'
);
'WwWwWw.mysql.com'
//替换后的
|
#mysql 中的replace用法
#用法1.replace into
1
|
replace into replace into table (id,name) values(
'1'
,
'aa'
),(
'2'
,
'bb'
);
|
此语句的作用是向表table中插入两条记录。
如果主键id为1或2不存在,就相当于
1
|
insert into table (id,name) values(
'1'
,
'aa'
),(
'2'
,
'bb'
)
|
如果存在相同的值则不会插入数据
#用法2.replace(object,search,replace)
把object中出现search的全部替换为
1
|
select replace(
'www.163.com'
,
'w'
,
'Ww'
) WwW wWw.163.com
|
例:把表table中的name字段中的 aa替换为bb
1
|
update table set name=replace(name,
'aa'
,
'bb'
)
|
Sql Server 中 text或ntext 字段内容替换
刚开始,Update AA 表 Set xx字段=Replace(xx字段,"要替换的","特定串") ,出现错误:函数 replace 的参数 1 的数据类型 ntext 无效。
1
2
|
Update article set heading=Replace(convert(nvarchar(4000),heading),
'<script></script>'
,
''
)
update 表名 set text类型字段名=replace(convert(varchar(8000),text类型字段名),
'要替换的字符'
,
'替换成的值'
)
|
varchar和nvarchar类型是支持replace,所以如果你的text/ntext不超过8000/4000可以先转换成前面两种类型再使用replace。
1
2
|
update 表名 set text类型字段名=replace(convert(varchar(8000),text类型字段名),
'要替换的字符'
,
'替换成的值'
)
update 表名 set ntext类型字段名=replace(convert(nvarchar(4000),ntext类型字段名),
'要替换的字符'
,
'替换成的值'
)
|
如果text/ntext超过8000/4000,看如下例子:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
|
declare
@pos int
declare
@len int
declare
@str nvarchar(4000)
declare
@des nvarchar(4000)
declare
@
count
int
set @des =
'<requested_amount+1>'
--要替换成的值
set @len=len(@des)
set @str=
'<requested_amount>'
--要替换的字符
set @
count
=0--统计次数.
WHILE 1=1
BEGIN
select @pos=patINDEX(
'%'
+@des+
'%'
,propxmldata) - 1
from 表名
where 条件
IF @pos>=0
begin
DECLARE @ptrval binary(16)
SELECT @ptrval = TEXTPTR(字段名)
from 表名
where 条件
UPDATETEXT 表名.字段名 @ptrval @pos @len @str
set @
count
=@
count
+1
end
ELSE
break
;
END
select @
count
|