str_replace函數的語法很簡單:
replace("string_expression1", "string_expression2", "string_expression3")
就是:將字符串1中所包含的所有 的字符串2都用字符串3統統替換。
一個簡單的例子:
- 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 ',' ','')
但是很可惜,執行失敗。
- 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 相當於“”(空字符)。
""相當於" "
示例:
- 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 相當於“”(空字符)
示例如下:
- 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 相當於“”(空字符),""相當於" " 。其它都是正常的。