sql---str_replace()用法

str_replace函數的語法很簡單:

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

 

就是:將字符串1中所包含的所有 的字符串2都用字符串3統統替換。

一個簡單的例子:

[c-sharp] view plain copy
  1. 1> select str_replace('This is Andkylee!My nAme is andkylee!','A','a')  
  2. 2> go  
  3.  -------------------------------------  
  4.  This is andkylee!My name is andkylee!  
  5. (1 row affected)  

 

但是, 網上有人發帖說str_replace不能替換字符串中的空格爲“(也就是說刪除字符串中的所有空格)。不看官方文檔,想當然的就寫出來這樣的語句:select str_replace('123 456 ',' ','')

但是很可惜,執行失敗。

[c-sharp] view plain copy
  1. 1> select len('123 456 '),str_replace('123 456 ',' ','') ,len(str_replace('123 456 ',' ',''))  
  2. 2> go  
  3.  ----------- -------- -----------  
  4.            8 123 456            8  
  5. (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. 1> select str_replace("cde fghi ","","_")  
  2. 2> go  
  3.  ---------  
  4.  cde_fghi_  
  5. (1 row affected)  
  6. 1> select str_replace("cde fghi "," ","_")  
  7. 2> go  
  8.  ---------  
  9.  cde_fghi_  
  10. (1 row affected)  

兩個空格還是2個空格意思:

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

 ---------
 cde fghi

(1 row affected)

 

 

NULL 相當於“”(空字符)

示例如下:

[c-sharp] view plain copy
  1. 1> select str_replace("cde fghi "," ",null),len(str_replace("cde fghi "," ",null))  
  2. 2> go  
  3.  --------- -----------  
  4.  cdefghi             7  
  5. (1 row affected)  
  6. 1> select str_replace("cde fghi ","",null),len(str_replace("cde fghi "," ",null))  
  7. 2> go  
  8.  --------- -----------  
  9.  cdefghi             7  
  10. (1 row affected)  


總結:

在函數str_replace中NULL 相當於“”(空字符),""相當於" " 。其它都是正常的。

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章