search
HomeDatabaseMysql TutorialSQL 截取字符串应用代码

字符串截取函数,只限单字节字符使用(对于中文的截取时遇上奇数长度是会出现乱码,需另行处理),本函数可截取字符串指定范围内的字符。

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();
}
Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
SQL Server使用CROSS APPLY与OUTER APPLY实现连接查询SQL Server使用CROSS APPLY与OUTER APPLY实现连接查询Aug 26, 2022 pm 02:07 PM

本篇文章给大家带来了关于SQL的相关知识,其中主要介绍了SQL Server使用CROSS APPLY与OUTER APPLY实现连接查询的方法,文中通过示例代码介绍的非常详细,下面一起来看一下,希望对大家有帮助。

SQL Server解析/操作Json格式字段数据的方法实例SQL Server解析/操作Json格式字段数据的方法实例Aug 29, 2022 pm 12:00 PM

本篇文章给大家带来了关于SQL server的相关知识,其中主要介绍了SQL SERVER没有自带的解析json函数,需要自建一个函数(表值函数),下面介绍关于SQL Server解析/操作Json格式字段数据的相关资料,希望对大家有帮助。

聊聊优化sql中order By语句的方法聊聊优化sql中order By语句的方法Sep 27, 2022 pm 01:45 PM

如何优化sql中的orderBy语句?下面本篇文章给大家介绍一下优化sql中orderBy语句的方法,具有很好的参考价值,希望对大家有所帮助。

Monaco Editor如何实现SQL和Java代码提示?Monaco Editor如何实现SQL和Java代码提示?May 07, 2023 pm 10:13 PM

monacoeditor创建//创建和设置值if(!this.monacoEditor){this.monacoEditor=monaco.editor.create(this._node,{value:value||code,language:language,...options});this.monacoEditor.onDidChangeModelContent(e=>{constvalue=this.monacoEditor.getValue();//使value和其值保持一致i

一文搞懂SQL中的开窗函数一文搞懂SQL中的开窗函数Sep 02, 2022 pm 04:55 PM

本篇文章给大家带来了关于SQL server的相关知识,开窗函数也叫分析函数有两类,一类是聚合开窗函数,一类是排序开窗函数,下面这篇文章主要给大家介绍了关于SQL中开窗函数的相关资料,文中通过实例代码介绍的非常详细,需要的朋友可以参考下。

Monaco Editor怎么实现SQL和Java代码提示Monaco Editor怎么实现SQL和Java代码提示May 11, 2023 pm 05:31 PM

monacoeditor创建//创建和设置值if(!this.monacoEditor){this.monacoEditor=monaco.editor.create(this._node,{value:value||code,language:language,...options});this.monacoEditor.onDidChangeModelContent(e=>{constvalue=this.monacoEditor.getValue();//使value和其值保持一致i

如何使用exp进行SQL报错注入如何使用exp进行SQL报错注入May 12, 2023 am 10:16 AM

0x01前言概述小编又在MySQL中发现了一个Double型数据溢出。当我们拿到MySQL里的函数时,小编比较感兴趣的是其中的数学函数,它们也应该包含一些数据类型来保存数值。所以小编就跑去测试看哪些函数会出现溢出错误。然后小编发现,当传递一个大于709的值时,函数exp()就会引起一个溢出错误。mysql>selectexp(709);+-----------------------+|exp(709)|+-----------------------+|8.218407461554972

springboot配置mybatis的sql执行超时时间怎么解决springboot配置mybatis的sql执行超时时间怎么解决May 15, 2023 pm 06:10 PM

当某些sql因为不知名原因堵塞时,为了不影响后台服务运行,想要给sql增加执行时间限制,超时后就抛异常,保证后台线程不会因为sql堵塞而堵塞。一、yml全局配置单数据源可以,多数据源时会失效二、java配置类配置成功抛出超时异常。importcom.alibaba.druid.pool.DruidDataSource;importcom.alibaba.druid.spring.boot.autoconfigure.DruidDataSourceBuilder;importorg.apache.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment