截取字符串常用到以下3个函数:
1.left(string, length):返回string字符串从左边起length长度的字符
2.right(string, length):返回string字符串从右边起length长度的字符
3.substring(string, start, length):返回string字符串从start开始length长度的字符
示例:
教师信息表的定义如下:
CREATE TABLE [dbo].[teacher_info](
[teacher_id] [char](6) NOT NULL,
[name] [nvarchar](4) NOT NULL,
[gender] [nchar](1) NULL,
[age] [int] NULL,
[tech_title] [nvarchar](5) NULL,
[telephone] [varchar](12) NULL,
[salary] [decimal](7, 2) NULL,
[course_id] [char](10) NULL
)
已知所有老师的姓氏为单姓
1.分别用left函数、substring函数,根据教师信息表(teacher_info)中教师的姓名(name)获取每个老师的姓为surname字段:
select teacher_id
,name
,left(name,1) surname
,gender
,age
,tech_title
,telephone
,salary
,course_id
from [student].[dbo].[teacher_info]
select teacher_id
,name
,substring(name,1,1) surname
,gender
,age
,tech_title
,telephone
,salary
,course_id
from [student].[dbo].[teacher_info]
2.分别用right函数、substring函数,根据教师表(teacher_info)中教师的姓名(name)获取每个老师的名为name_teacher字段:
select teacher_id
,name
,right(name,len(name)-1) name_teacher
,gender
,age
,tech_title
,telephone
,salary
,course_id
from [student].[dbo].[teacher_info]
select teacher_id
,name
,substring(name,2,len(name)-1) name_teacher
,gender
,age
,tech_title
,telephone
,salary
,course_id
from [student].[dbo].[teacher_info]
注:len(string) 返回string字符串长度
end
有兴趣的小伙伴可以关注“SQL数据库笔记”公众号,一起学习吧!
|