SQL截取字符串


SUBSTRING 
返回字符、binary、text      或      image      表達式的一部分。有關可與該函數一起使用的有效      Microsoft®      SQL      Server™      數據類型的更多信息,請參見數據類型。   

語法 
SUBSTRING      (      expression      ,      start      ,      length      )   

參數 
expression 

是字符串、二進制字符串、text、image、列或包含列的表達式。不要使用包含聚合函數的表達式。 

start 

是一個整數,指定子串的開始位置。 

length 

是一個整數,指定子串的長度(要返回的字符數或字節數)。

substring() 
——任意位置取子串 

left() 
right() 
——左右兩端取子串 

ltrim() 
rtrim() 
——截斷空格,沒有trim()。 

charindex() 
patindex() 
——查子串在母串中的位置,沒有返回0。區別:patindex支持通配符,charindex不支持。

函數功效:
字符串截取函數,只限單字節字符使用(對於中文的截取時遇上奇數長度是會出現亂碼,需另行處理),本函數可截取字符串指定范圍內的字符。

應用范圍:
標題、內容截取

函數格式:
string substr ( string string, int start [, int length])
參數1:處理字符串
參數2:截取的起始位置(第一個字符是從0開始)
參數3:截取的字符數量
substr()更多介紹可在PHP官方手冊中查詢(字符串處理函數庫)

舉例:
substr("ABCDEFG", 0);     //返回:ABCDEFG,截取所有字符
substr("ABCDEFG", 2);     //返回:CDEFG,截取從C開始之后所有字符
substr("ABCDEFG", 0, 3); //返回:ABC,截取從A開始3個字符
substr("ABCDEFG", 0, 100); //返回:ABCDEFG,100雖然超出預處理的字符串最長度,但不會影響返回結果,系統按預處理字符串最大數量返回。
substr("ABCDEFG", 0, -3); //返回:EFG,注意參數-3,為負值時表示從尾部開始算起,字符串排列位置不變

例子:


1.截取已知長度的函數


  A.截取從字符串左邊開始N個字符

     Declare @S1 varchar(100)
     Select @S1='http://www.163.com'
     Select Left(@S1,4)
     ------------------------------------
     顯示結果: http

  B.截取從字符串右邊開始N個字符(例如取字符www.163.com)

     Declare @S1 varchar(100)
     Select @S1='http://www.163.com'
     Select right(@S1,11)  
     ------------------------------------
     顯示結果: www.163.com

  C.截取字符串中任意位置及長度(例如取字符www)

     Declare @S1 varchar(100)
     Select @S1='http://www.163.com'
     Select SUBSTRING(@S1,8,3)  
     ------------------------------------
     顯示結果: www.163.com


     以上例子皆是已知截取位置及長度,下面介紹未知位置的例子

2.截取未知位置的函數


  A.截取指定字符串后的字符串(例如截取http://后面的字符串)

     方法一:

     Declare @S1 varchar(100)
     Select @S1='http://www.163.com'  
     Select Substring(@S1,CHARINDEX('www',@S1)+1,Len(@S1))
     /*此處也可以這樣寫:Select Substring(@S1,CHARINDEX('//',@S1)+2,Len(@S1))*/

     ------------------------------------
     顯示結果: www.163.com


     需要注意:CHARINDEX函數搜索字符串時,不區分大小寫,因此CHARINDEX('www',@S1)也可以寫成CHARINDEX('WWW',@S1)

     方法二:(與方法一類似)

     Declare @S1 varchar(100)
     Select @S1='http://www.163.com'  
     Select Substring(@S1,PATINDEX('%www%',@S1)+1,Len(@S1))
     --此處也可以這樣寫:Select Substring(@S1,PATINDEX('%//%',@S1)+2,Len(@S1))
     ------------------------------------
     顯示結果: www.163.com  

   函數PATINDEX與CHARINDEX區別在於:前者可以參數一些參數,增加查詢的功能

     方法三:

     Declare @S1 varchar(100)
     Select @S1='http://www.163.com'  
     Select REPLACE(@S1,'http://','')
     ------------------------------------
     顯示結果: www.163.com

  利用字符替換函數REPLACE,將除需要顯示字符串外的字符替換為空

     方法四:

     Declare @S1 varchar(100)
     Select @S1='http://www.163.com'  
     Select STUFF(@S1,CHARINDEX('http://',@S1),Len('http://'),'')
     ------------------------------------
     顯示結果: www.163.com  


  函數STUFF與REPLACE區別在於:前者可以指定替換范圍,而后者則是全部范圍內替換

  B.截取指定字符后的字符串(例如截取C:\Windows\test.txt中文件名)
       與A不同的是,當搜索對象不是一個時,利用上面的方法只能搜索到第一個位置

     方法一:

     Declare @S1 varchar(100)
     Select @S1='C:\Windows\test.txt'
     select right(@S1,charindex('\',REVERSE(@S1))-1)
     -------------------------------------
     顯示結果: text.txt


利用函數REVERSE獲取需要截取的字符串長度

  

substr()

例子:

private void DDL_AreaBind()
          {
              conn = new SqlConnection(ConfigurationManager.ConnectionStrings["strcon"].ConnectionString);
              string str = "0000";
              cmd = new SqlCommand("select AreaID,Name=ltrim(Name) from Area where    right(AreaID,4) ='" + str + "'", conn);
              SqlDataAdapter sda = new SqlDataAdapter(cmd);
              sda.Fill(ds, "area");
              this.ddl_area.DataSource = ds.Tables["area"].DefaultView;
              this.ddl_area.DataTextField = "Name";
              this.ddl_area.DataValueField = "AreaID";
              this.ddl_area.DataBind();

            
              cmd = new SqlCommand("select * from Area    ", conn);
              cmd.CommandType = CommandType.Text;
              SqlDataAdapter adapter = new SqlDataAdapter(cmd);
              adapter.Fill(ds, "city");
              this.ddl_city.DataSource = ds.Tables["city"].DefaultView;
              this.ddl_city.DataTextField = "Name";
              this.ddl_city.DataValueField = "AreaID";
              this.ddl_city.DataBind();
          }

protected void ddl_area_SelectedIndexChanged(object sender, EventArgs e)
          {
              conn = new SqlConnection(ConfigurationManager.ConnectionStrings["strcon"].ConnectionString);
              this.ddl_city.Enabled = true;
              string str1="0000";
              cmd = new SqlCommand("select AreaID,Name from Area where substring(AreaID,1,2)='" + this.ddl_area.SelectedValue.Substring(0,2)    + "' AND substring(AreaID,3,4) <> '0000' AND substring(AreaID,5,2)='00'    ", conn);
              cmd.CommandType = CommandType.Text;
              SqlDataAdapter adapter = new SqlDataAdapter(cmd);
              DataSet ds = new DataSet();
              adapter.Fill(ds, "city");
              this.ddl_city.DataSource = ds.Tables["city"].DefaultView;
              this.ddl_city.DataTextField = "Name";
              this.ddl_city.DataValueField = "AreaID";
              this.ddl_city.DataBind();
          }

 

PS:

最近項目中用到比較少見的SQL語句,分享一下:

查詢祖先節點
select * from 目錄表_數據庫  where ID<>-1 and datatype<>1 and datatype<>2 connect by prior FATHERID=ID start with ID=28 order by 目錄級別,ID

查詢子孫節點:
select * from 目錄表_數據庫  where ID<>-1 and datatype<>1 and datatype<>2 connect by prior ID=FATHERID start with ID=28 order by 目錄級別,ID


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM