您的位置:首页 > 数据库

sql---str_replace()用法

2016-07-26 08:58 337 查看
str_replace函数的语法很简单:

                     replace("string_expression1", "string_expression2", "string_expression3")

 

就是:将字符串1中所包含的所有 的字符串2都用字符串3统统替换。

一个简单的例子:

[c-sharp] view
plain copy

1> select str_replace('This is Andkylee!My nAme is andkylee!','A','a')  

2> go  

 -------------------------------------  

 This is andkylee!My name is andkylee!  

(1 row affected)  

 

但是, 网上有人发帖说str_replace不能替换字符串中的空格为“(也就是说删除字符串中的所有空格)。不看官方文档,想当然的就写出来这样的语句:select str_replace('123 456 ',' ','')

但是很可惜,执行失败。

[c-sharp] view
plain copy

1> select len('123 456 '),str_replace('123 456 ',' ','') ,len(str_replace('123 456 ',' ',''))  

2> go  

 ----------- -------- -----------  

           8 123 456            8  

(1 row affected)  

如上可以看到select str_replace('123 456 ',' ','')并没有替换其中的空格为空(亦即删除其中的所有空格),用函数str_replace执行前后的字符串是相同的。

 

通过查阅官方文档中关于str_replace的介绍,有下面的两点需要注意:

1. Adaptive Server 将空字符串常量自动转换为 1 个空格的字符串,以便将该字符串与 NULL 值区分开。

2. str_replace 在第三个参数中接受 NULL,将其视为尝试用 NULL 替换 string_expression2,有效地将 str_replace 转换成“字符串切除”

操作。


 

这两条的意思是说:在函数str_replace中""相当于" ", NULL 相当于“”(空字符)。

 

 ""相当于" "

示例:

[c-sharp] view
plain copy

1> select str_replace("cde fghi ","","_")  

2> go  

 ---------  

 cde_fghi_  

(1 row affected)  

1> select str_replace("cde fghi "," ","_")  

2> go  

 ---------  

 cde_fghi_  

(1 row affected)  

两个空格还是2个空格意思:

1> select str_replace("cde fghi ","  ","_")

2> go

 ---------

 cde fghi

(1 row affected)

 

 

NULL 相当于“”(空字符)

示例如下:

[c-sharp] view
plain copy

1> select str_replace("cde fghi "," ",null),len(str_replace("cde fghi "," ",null))  

2> go  

 --------- -----------  

 cdefghi             7  

(1 row affected)  

1> select str_replace("cde fghi ","",null),len(str_replace("cde fghi "," ",null))  

2> go  

 --------- -----------  

 cdefghi             7  

(1 row affected)  

总结:

在函数str_replace中NULL 相当于“”(空字符),""相当于" " 。其它都是正常的。

 
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: