SQL:
SQL 中的 SUBSTRING 函數是用來抓出一個欄位資料中的其中一部分。這個函數的名稱在不同的資料庫中不完全一樣:MySQL: SUBSTR( ), SUBSTRING( )
Oracle: SUBSTR( )
SQL Server: SUBSTRING( )
最常用到的方式如下 (在這裡我們用SUBSTR( )為例):
SUBSTR (str, pos)以上語法的意思是,由輸入的字串(str)中,選出所有從第(pos)位置開始的字元。
請注意,這個語法不適用於SQL Server上。
如要在SQL Server執行時會出現下面錯誤
SQL Server 2012 測試結果 |
SUBSTR (str, pos, len)以上語法的意思是,由輸入的字串(str)中,的第(pos)位置開始,選出接下去的(len)個字元。
以下範例:
SELECT SUBSTRING('abcdefghijk', 1, 3) //abc SELECT SUBSTRING('abcdefghijk', 3, 2) //cd SELECT SUBSTRING('abcdefghijk', -3, 2) //空字串
MS SQLServer 2012
Syntax:Returns part of a character, binary, text, or image expression.
SUBSTRING ( expression, start, length )
Arguments:
expression
A character string, binary string, text, image, a column, or an expression that includes a column. Do not use expressions that include aggregate functions.
start
An integer or an expression that can be implicitly converted to int, which specifies where the substring begins.
length
An integer or an expression that can be implicitly converted to int, which specifies the length of the substring.
Return Value:
Returns character data if expressionis one of the supported character data types. Returns binary data if expressionis one of the supported binary data types. If start = 1, then the substring begins from the first character of the expression.
The returned string is the same type as the given expression with the exceptions shown in the following table.
Code Example:
The following example returns the initial of the first name and the full last name for each employee in the Employees table.
SELECT SUBSTRING([First Name],1,1) AS Initial, [Last Name] FROM EmployeesThis is the result set:
Initial Last Name ---------------------------- N Davolio A Fuller J Leverling M Peacock S Buchanan M Suyama R King L Callahan A Dodsworth A Hellstern T Smith C Patterson J Brid X Martin L Pereira (15 rows affected)
參考資料(MSDN):http://msdn.microsoft.com/zh-tw/library/ms187748.aspx
JAVA
String 類別 (class) 有 substring() 方法 (method) ,回傳指定範圍的子字串方法 | 描述 |
---|---|
String substring(int beginIndex, int endIndex) | 回傳從 beginIndex 到 endIndex 之間的子字串 |
String substring(int beginIndex) | 回傳從 beginIndex 到結尾的子字串 |
public class Test { public static void main(String[] args) { String a = "台上一分鐘,台下十年功。"; String b = "台上一分鐘,台下十年功。"; String c = "台上一分鐘,台下十年功。"; System.out.println(a.substring(0, 7)); System.out.println(b.substring(4)); System.out.println(c.substring(3, 6)); } } /* 《程式語言教學誌》的範例程式 http://pydoing.blogspot.com/ 檔名:SubstringDemo.java 功能:示範物件導向的基本觀念 作者:張凱慶 時間:西元 2010 年 10 月 */
範例輸出結果 |
沒有留言:
張貼留言