码迷,mamicode.com
首页 > 数据库 > 详细

sql-server笔记V20170429

时间:2017-04-30 01:09:46      阅读:286      评论:0      收藏:0      [点我收藏+]

标签:rollback   添加   sda   向上取整   gad   cap   示例   身份证   表示范围   

--快捷键:关闭显示结果:ctrl+R
--一、创建表,删除表
/*--创建表
--格式:
create table 表名
(
	字段名 数据类型 [约束条件(identity(1,1);primary key)],
	字段名2 数据类型 [约束条件]
	
)
*/

/*
--删除数据库和表
drop 数据库名
drop table 表名
*/

/*
--创建table学生表
create table TblStudent
(
	tSId int identity(1,1) primary key,
	tSName nvarchar(50) not null,
	tSGender nchar(1),
	tSAge int,
	tSBirthday datetime,
	tSCardId VARCHAR(18),
	tSClassId INT

)
*/

/*
--创建table教室表
create table TblClass
(
	tClassId int identity(1,1) primary key,
	tClassName nvarchar(50)
	
)
*/

/*
--创建table成绩表
create table TblScore
(
	tScoreId int identity(1,1) primary key,
	tSid int not null,
	tEnglish float,
	tMath float
)
*/


use HeiMal3
--创建table教师表
create table Tblteacher
(
	tTId int identity(1,1) primary key,
	tTName nvarchar(50) not null,
	tTGender nchar(1),
	tTAge int,
	tTSalary money,
	tTBirthday datetime,
	tTJionDate datetime
)


/*
--创建部门表
create table Departments
(
	DepID int identity(1,1) primary key,
	DepName nvarchar(50)  null
)
*/



/*
--创建员工表
--<员工表>:员工号id,身份证号,姓名,性别,入职日期,年龄,地址,电话.所属部门,email
create table Employees
(
	EmpID int identity(1,1) primary key,
	EmpIDCard varchar(18) not null,
	EmpName nvarchar(50) null,
	EmpGender bit not null,
	EmpJionDate datetime,
	EmpAge int,
	EmpAddress nvarchar(300),
	EmpPhone varchar(100),
	Empmaill varchar(100),
	DeptID int not null,
	
	
)
*/


--创建table人表
create table TblPerson
(
	autoId int identity(1,1) primary key,
	uName nvarchar(10),
	age int,
	height int,
	gendder bit
)

--二、插入表
--格式:
--insert into 表名(列1,列2,列3) values(值1,值2,值3)
--连续插入多行
--insert into 表名(列1,列2,列3) values(值1,值2,值3),(值1,值2,值3),(值1,值2,值3)

--向班级表插入一条记录
--自动编号列,默认就会自动增长,所以不需要(默认情况下也不能向自动编号列插入值)
/*
insert into TblClass(tClassName) values (‘.net黑马一期‘)

--查询显示出来
select * from TblClass
*/
/*
--向学生表插入一条记录
insert into 
TblStudent(tSName,tSGender,tSAge,tSBirthday,tSCardId,tSClassId)
values(‘熊丽‘,‘女‘,‘北京市海定区‘,16,‘1998-5-5‘,‘123456789654123698‘,1)
*/
/*

insert into 
TblStudent(tSName,tSGender,tSAddress,tSAge,tSBirthday,tSCardId,tSClassId)
values(‘刘天龙‘,‘男‘,‘北京海钉区‘,17,‘1997-5-5‘,‘12345784663135‘,1)

insert into 
TblStudent
values(‘刘天龙12‘,‘男‘,‘北京海钉区‘,17,‘1997-5-5‘,‘12345784663135‘,1)
select * from TblStudent

insert into TblStudent(tSName,tsgender,tSAge)
values(‘石荣‘,‘女‘,15)
*/
/*
--向自动编号插入值(插入不了)
insert into TblClass(tClassId,tClassName)
values(500,‘.net黑马二期‘)
--方法
--向自动编号列插入值
--启动某个表的“自动编号列”手动插入值的功能
set identity_insert TblClass on
insert into TblClass(tClassId,tClassName)
values(500,‘.net黑马二期‘)
set identity_insert TblClass off
select * from TblClass

*/
insert into TblClass(tClassName)
values(‘.net黑马三期‘)

--字符串后面有中文,则前面加N
insert into TblClass(tClassName)
values(N‘.net黑马四期‘)

--三、更新列表
--格式:
--update 表名 set 列=新值,列2=新值2,......where 条件

use HeiMal3
select * from TblStudent

--如果不加where 条件,那么表示对表中所有的数据都进行修改,所以一定要加where条件

update TblStudent set tSAge=tSAge-1,tSName=tSName+‘(女)‘ where tSGender=‘女‘

--update 表名 set age=18 where name=‘王灿‘or age<25
--update 表名 set age=30 where (age>20and age<30) or age=50

--四、删除数据语句:
--delete from 表名 where ......
--delete 语句如果不加where 条件,表示将表中所有的数据都删除,加了where条件后,只会按照where条件进行删除

select * from TblStudent

--删除table学生表,不需要加在delete 后面 加 * 无条件进行删除,只有查询的时候带* 号
delete   from TblStudent

insert into 
TblStudent
values(‘刘天龙12‘,‘男‘,‘北京海钉区‘,17,‘1997-5-5‘,‘12345784663135‘,1)
select * from TblStudent

--删除所有性别为‘女‘,同事年龄小于20岁的

delete from TblStudent where tSGender=‘女‘ and tSAge<20

--delete只是删除数据,表还在,和 drop不同

--删除表中的全部数据:
--1.delete from 表
--2.truncate table 表
--如果确定要删除表中全部数据,那么建议使用truncate
--truncate特点:
--1>truncate 语句不能跟where条件(无法根据条件进行删除,只能全部删除数据)
--2>同时自动编号恢复到初始值。delete 不能恢复到初始值
--3>使用truncate 删除表中所有数据比delete的效率高
--4>truncate 删除数据,不触发delete触发器。
select * from Tblteacher

/*
--向Tblteacher插入数据
insert  into Tblteacher(tTName,tTGender,tTAge,tTSalary,tTBirthday,tTJionDate)
values(‘苏坤‘,‘男‘,18,10060,‘1990-09-09‘,‘2010-12-15‘)
insert  into Tblteacher(tTName,tTGender,tTAge,tTSalary,tTBirthday,tTJionDate)
values(‘王二‘,‘男‘,18,10060,‘1990-09-09‘,‘2010-12-15‘),
(‘李四‘,‘男‘,18,10060,‘1990-09-09‘,‘2010-12-15‘),
(‘苏折坤‘,‘男‘,18,10060,‘1990-09-09‘,‘2010-12-15‘),
(‘苏大坤‘,‘男‘,18,10060,‘1990-09-09‘,‘2010-12-15‘),
(‘李梅‘,‘女‘,19,30060,‘1995-09-09‘,‘2015-12-15‘)
*/

--1.使用insert into 向TblTeacher表插入2条数据
select * from Tblteacher
insert into Tblteacher
values(‘刘琦‘,‘男‘,30,150000,‘1983-10-10‘,‘2012-5-8‘)

--2.向TblPerson表中插入2条数据.

select * from TblPerson
insert into TblPerson
values(‘百川儿‘,21,175,1),(‘小李‘,22,170,0)


--3.给TblScore中的studentId是1的英语成绩加10分
select * from TblScore
insert into TblScore
values(1,96,85),(2,93,88),(1,98,88)

update TblScore set tEnglish=tEnglish+10 where tSid=1

--3.1给TblScore中的studentId是1的英语成绩加10分,分数不能超过100.
--分数超过100的,都设置为100
--3.2给分数没有超过100的,每人加10分
select * from TblScore
update TblScore set tEnglish=100 where(tEnglish+10>100 or tEnglish+10=100)
update TblScore set tEnglish=tEnglish+10 where tEnglish+10<100

--4.所有男童鞋的年龄减1岁
select * from TblStudent
update TblStudent set tSAge=tSAge-1 where tSGender=‘男‘

--5.删除工资大于2000的老师
select * from Tblteacher
delete from Tblteacher where tTSalary>20000

--6.删除表,把自动增长列的值还原成种子(还原成默认值,最开始的状态,从1开始,每增加一次加1)
truncate table TblTeacher


--四、建立约束


--创建部门表
create table Department
(
	Depid int identity(1,1),
	DepName varchar(50)
)





--创建员工表

create table Employees
(
	EmpId int identity(1,1),
	EmpName varchar(50),
	EmpGender char(2),
	EmpAge int,
	Empmail varchar(100),
	EmpAddress varchar(500),

)

select * from Employees
select * from Department


--4.1非空约束:不能为空
--4.2主键约束(PK) primary key constraint 唯一且不能空
--4.3唯一约束(UQ) unique constraint 唯一,允许为空,但只能出现一次
--4.4默认约束(DF) default constraint 默认值
--4.5检查约束(Ck)check constraint 范围以及格式限制
--4.6外键约束(Fk) foreign key constraint表关系

--备注:当主键表中一个值被外键表被引用,则删除不了主键中的值,除非外键表不引用主键表

/*
--初始化表
truncate table TblScore
truncate table TblStudent
*/


--五、通过sql进行设置约束

/*--删除表,重新新建表
drop table Department
drop table Employees
*/

--5.1修改表结构。删除其中一列
--结构:
--alter table 表名 drop column EmpAddress
alter table Employees drop column EmpAddress
select * from Employees

--5.2增加一列EmpAddr nvarchar(1000)
--表中增加默认是列,所以不用写column
alter table Employees add EmpAddr nvarchar(1000)


--5.3修改表中,EmpEmaill的数据类型为varchar(200)

alter table Employees alter column Empmail varchar(200)

--5.4为EmpId增加一个主键约束
alter table Employees add constraint PK_Employees_EmpId primary key(EmpId)


--5.5为EmpName增加一个非空约束(修改列,由null修改为not null)

alter table Employees alter column EmpName varchar(50) not null

--5.6为EmpName增加唯一约束

alter table Employees add constraint UQ_Employees_EmpName unique(EmpName)

--5.7为性别增加一个默认约束,默认为‘男‘
alter table Employees add constraint DF_Employees_EmpGender default(‘男‘) for EmpGender

--5.8为性别增加一个检查约束,要求性别只能是:‘男‘ or ‘女‘
alter table Employees add constraint CK_Employees_EmpGender check(EmpGender=‘男‘ or EmpGender=‘女‘) 
--为年龄增加一个检查约束:年龄必须在0--120岁之间。
alter table Employees add constraint CK_Employees_EmpAge check(EmpAge>=0 and EmpAge<=120)

select * from Department
select * from Employees
--5.9为部门表Department表设置主键,主键列是:DepId

alter table Department add constraint PK_Department_DepId primary key(DepId)

alter table Employees alter column 

--5.10为员工表中加入外键,增加一个DepId
alter table Employees drop column DepId
alter table Employees add EmpDepId int not null


--5.11添加外键约束
alter table Employees add constraint FK_Employees_Department foreign key(EmpDepId) references Department(Depid)



--5.12删除约束
--格式:
--alter table Employees drop constraint 外键1,外键2,外键3,
alter table Employees drop constraint FKEmployees_Department,PK_Department_DepId

--5.13通过一条代码增加多个约束
--格式:
--
alter table Employees add 
constraint FK_Employees_Department foreign key(EmpDepId) references Department(Depid),
constraint PK_Department_DepId primary key(DepId),
constraint CK_Employees_EmpAge check(EmpAge>=0 and EmpAge<=120)


---备注:在创建表的时候吧约束就加上

drop table Department
drop table Employees
create table Department
(
	DepId int identity(1,1) primary key,
	DepName varchar(50) not null unique
)

--创建部门表
create table Department
(
	Depid int identity(1,1) primary key,
	DepName varchar(50) not null unique
)





--创建员工表

create table Employees
(
	EmpId int identity(1,1) primary key ,
	EmpName varchar(50) not null unique check(len(EmpName)>2) ,
	EmpGender char(2) default(‘男‘),
	EmpAge int check(EmpAge>0 and EmpAge<120),
	Empmail varchar(100) unique,
	EmpAddress varchar(500) not null,
	EmpDepId int foreign key references Department(DepId)  on delete cascade
	--EmpDepId int foreign key references Department(DepId)  on delete cascade //可以实现级联删除

)



--六、数据查询(****)
--显示所有行,所有列
--* 表示所有列
--查询语句中没有where条件,表示查询所有行
--先执行from语句,再执行select 语句
select * 
from Tblteacher

--只查询部分列
select tTid,tTname,tTGender from Tblteacher

--根据条件,只查询部分行
select  *  from Tblteacher where tTId=5

--给查询结果的列起别名,也可以把 as  省略掉
select tTid as 编号,tTname as 姓名,tTGender as 性别 from Tblteacher


--格式变换,方便查看
select 
	tTid as ‘(编号)‘,
	tTname as 姓名,
	tTGender as 性别
from Tblteacher


--备注:并不是select 必须和from 一起使用
--获取当前的时间
select GETDATE() 当前系统时间

--七、去掉重复
--distinct 是针对已经查询出的结果后去除重复
select   * from Tblteacher

select  distinct * from Tblteacher

select distinct tTGender from Tblteacher

--八、Top
--Top一般都与order by一起使用

------------排序
--order by 列名
--8.1按照年龄,降序排序
update Tblteacher set tTAge=16 where tTId=1
select * from Tblteacher order by tTAge desc


--8.2按照年龄,升序排序,
--备注:默认就是升序排序
select * from Tblteacher order by tTAge

--排序后,进行筛选前多少列
--显示前2条 top后面都有 * 号
select top 2 * from Tblteacher order by tTAge

--显示前20% 条数据,向上取整
select top 20 percent * from Tblteacher order by tTAge desc



--九、聚合函数--把多条聚合在一起,必须先进行分类。先分组再统计


--9.1统计出所有人的年龄的总和----sum()
select * from Tblteacher
select SUM(tTAge) as 年龄总和  from Tblteacher

--9.2统计表中有多少条记录----count()
select COUNT(*) from Tblteacher

--9.3计算平均年龄---avg()
select AVG(tTAge) as 平均年龄  from Tblteacher
select AVG(tTAge*1.0) as 平均年龄  from Tblteacher
select ((select SUM(tTAge) as 年龄总和 from Tblteacher)*1.0/(select COUNT(*)  as 总数 from Tblteacher))  as 平均年龄
--9.4计算年龄最大--max()
select max(tTAge) as 最大年龄  from Tblteacher

--9.4计算年龄最小--min()
select min(tTAge) as 最小年龄  from Tblteacher

------聚合函数的一些其他问题
--聚合函数不统计空值--count(),avg()      不统计空值,sum()把空值默认为0进行计算
--select count(tTAge) from Tblteacher

--如果使用聚合函数的时候,没有手动用group by 分组,那么聚合函数会把整个表中的数据作为一组来统计


--十、条件查询——————————————————————————————
--格式:
--select 列
--from 表
--where 条件

select * from TblScore

insert into TblScore(tSid,tEnglish,tMath)
values(1,85,42),
(2,85,80),
(3,35,90)

insert into TblScore
values(1,45,56)
--查询没有及格的学习
select * from TblScore where tEnglish<60 or tMath<60

--c查询年龄包含在20--30岁之间男同学(包含20和30)
select * from TblStudent where tSAge>=20 and tSAge<=30 and tSGender=‘男‘
select * from TblStudent where tSAge between 20 and  30 and tSGender=‘男‘


--查询出所有班级ID为3,4,5的那些学生
select * from TblStudent where tSClassId =3 or tSClassId =4  or tSClassId =5
--简化版
select * from TblStudent where tSClassId in(3,4,5)

--如果后面的值是连续的,则简化成下面的代码(区间的话,执行速度高效)
select * from TblStudent where tSClassId >=3 and tSClassId<=5

--备注:对于in或者or查询,如果查询中的条件是连续的几个数字,最好使用>= <= 或者 between and 
--不要使用or 或者 in。提高效率


--十一、模糊查询(主要针对字符串)

--通配符:_ (下划线)  、  %  、  [] 、^
--:_(下划线)表示任意的单个字符

--查姓张,三个字(两个下划线)
select * from Tblteacher where tTName  like ‘苏__‘

--无论姓名的字数,只要是苏开头就可以
select * from Tblteacher where tTName  like ‘苏%‘


select * from Tblteacher where tTName  like ‘苏%‘ and LEN(tTName)=2



--:[](中括号)表示范围
--tTName:张a雨(女)(女)  把(女去掉)
update Tblteacher set tTName =REPLACE(tTName,‘(女)‘,‘‘)

--查询张开头,妹结尾,中间是数字

select * from Tblteacher where tTName like ‘张[0-9]妹‘
select * from Tblteacher where tTName like ‘张[a-z]妹‘
select * from Tblteacher where tTName like ‘张_妹‘

--张什么妹都可以,就是不是数字
select * from Tblteacher where tTName like ‘张[^0-9]妹‘

--数据中有名字中包含%。怎么查询(要进行转义)[放到中括号里]
select * from Tblteacher where tTName like ‘%\%%‘ --错误
select * from Tblteacher where tTName like ‘%[%]%‘--错误

--where columnA like ‘%5/%%‘ escape ‘/‘
select * from Tblteacher where tTName like ‘%/%%‘ escape ‘/‘

select * from Tblteacher where tTName like ‘%/]%‘ escape ‘/‘
select * from Tblteacher where tTName like ‘%/[%‘ escape ‘/‘
select * from Tblteacher where tTName like ‘%/[%/]%‘ escape ‘/‘


--十二、空值处理


select * from Tblteacher

--查询年龄中为空值的老师表
select * from Tblteacher where tTAge=null --查询不出来

--查询年龄中不是空值的老师表
select * from Tblteacher where tTAge<>null--查询不出来
select * from Tblteacher where tTAge=18 --查询出来
select * from Tblteacher where tTAge<>18 --查询出来

--备注:空值是空值(unknown),无法使用=或者<>进行比较
--判断null值必须使用is null 或者 is not null
select * from Tblteacher where tTAge is null
select * from Tblteacher where tTAge is  not null


--任何值和null计算都是null


---十三、order by排序
--1.降序order by 列名 desc 
--2.升序order by 列名 asc 或者order by 列名(默认是升序)
--3.order by 语句必须一定要放在整个sql语句的最后
--select * from 表名
--where ...
--gourp by...
--haing ...
--order by ...

--4.根据多列进行排序
--先根据英语成绩排序,再根据数学成绩排名
--先按照英语成绩进行排序,英语成绩相同时,再按照数学成绩进行排序
select * from TblScore order by tEnglish desc,tMath desc

--向TblScore添加一列(平均成绩)
alter table TblScore add tAvg int 
update TblScore set tAvg=(tEnglish+tMath)/2  where tScoreId =6
select *from TblScore

--显示的时候加入平均分
select * ,(tEnglish+tMath)/2 as 平均分

from TblScore
order by 平均分 desc 

--备注:执行顺序
select *  ---3执行
from TblScore ---1先执行
where tEnglish>=60 and tMath>=60 ----2执行
order by tEnglish desc,tMath desc  ---4最后



--top一般都要配合order by一起使用



--第十三章 数据分组


use HeiMal3

--分组一般都和聚合函数要一起连用
--对数据进行汇总统计
--对班级进行分组,并统计各班级人数
--查询每个班的班级ID和班级人数

select 
	tSClassId as 班级ID, 
	COUNT(*) as  班级人数
from TblStudent
group by tSClassId


--统计所有学生表中男同学与女同学的人数分别是多少?

select 
	tSGender as 性别, 
	COUNT(*) as  人数
from TblStudent
group by tSGender



--统计学生表中每个班的班级ID和班级中男同学的人数
select 
	tSClassId as 班级ID, 
	COUNT(*) as  男同学人数
from TblStudent
where tSGender=‘男‘
group by tSClassId
--先筛选,再分组


---只能出现分组中的列
--
select 
	sum(tsage)  年龄,
	tsgender as 性别,
	count(*) as 人数

from TblStudent
group by tsgender
--当使用了分组语句(group by)或者是聚合函数的时候,在select的查询列表中不能再包含其他列的别名。
--除非该列同时也出现了group by 子语句中,或者该列也包含了某个聚合函数中




--第十四章 having----对分组以后的数据进行筛选:
--having与where都是对数据进行筛选,where是对分组的每一行数据进行筛选,而
--having是对分组后的每一组数据进行筛选
select 
	tSClassId as 班级ID, 
	COUNT(*) as  男同学人数
from TblStudent
where tSGender=‘男‘
group by tSClassId
having COUNT(*)>5
order by 男同学人数 asc --进行排序
--5>select 5.1选择列, 5.2>distinct,5.3>top(应用top选项最后计算)
--1>from 表
--2>where 条件
--3>group by 列
--4>having 筛选条件
--6>order by 列



--备注:select 语句的出来顺序
--以下显示select语句的处理顺序
--1.from
--2.on
--3.join
--4.where
--5.group by
--6.with |cube 或with rollup
--7.having
--8.select
--9.distinct
--10.order by
--11.top


------------test------------------------
/*

select 商品名称,
		SUM(销售数量) as 销量
from MyOrder
group by 商品名称
order by sum(销售数量) desc



select 商品名称,
		SUM(销售数量*销售价格) as 各总价格
from MyOrder
group by 商品名称
having sum(销售数量*销售价格) >3000
order by sum(销售数量*销售价格) desc


select 购买人,
		sum(销售数量) as 可口可乐的数量
from MyOrder
where 商品名称=‘可口可乐‘
group by 购买人


*/

--当把select查询后的结果用作后面的查询,必须要起一个别名
--必须起别名!!!!!!!!!!!!!!
/*
select 
	SUM(T.销售数据) 喜爱度,
	T.购买人 客户
	
from (select * from MyOrder where 商品名称=‘可口可乐‘) as T
group by T.购买人
order by 喜爱度 desc
*/




---第十五章 类型转换函数
---------------------类型转换函数---------
select 100+200
select 100+‘1000‘
print ‘1000‘+100
select 100.0+‘1000‘

print ‘a‘+100

--cast(要转换的值,as 转换的类型)
--cast(表达式,as 数据类型)
select 100.0+CAST(‘1000‘ as int)
--convert(转换的类型,要转化的值)
--convert(数据类型,表达式)
select 100.0+convert(int, ‘1000‘)
select * from TblStudent
select ‘班级编号:‘+convert(char(1),1)

--当进行排序时,排序的对象(bid)是varchar,一般排序是对数字进行排序
--select * from 表名 order by convert(int,bid) desc

--时间转换 只能用convert
print getdate()
print convert(varchar(200),getdate(),111)--最后要查表


---第十六章 联合结果集,不是连接集.联合结果集(union)(集合运算符)(把多个表的行进行连接。如表1:5条记录,表2:4条记录;则联合就有9条记录)
--连接是把列进行连接~如:表1有3列,表2有4列,则连接有7列
--联合是把行进行连接

------------使用union联合结果集----------------
--------备注:列的类型兼容和数量必须是一样
--写法1:union all
select tTId ,tTName,tTGender,tTAge from Tblteacher
union all
select tSId,tSName,tSGender,tSAge from TblStudent


--写法2:去掉all 则union
select tTId ,tTName,tTGender,tTAge from Tblteacher
union 
select tSId,tSName,tSGender,tSAge from TblStudent
---使用union和union all都能进行联合,区别在于:使用union联合会去除重复/重新排列数据,而union all 不会去除重复也不会重复进行排列
--


---推荐使用union all ,不去重复.只看联合后的数据
--大多数,联合的时候不需要,进行去重,和重新

--从MyOrder 表中统计每种商品的销售总价,并且在底部做汇总

select 
	商品名称,
	sum(销售价格*销售数量) as 销售总价
from Myorder
group by 商品名称
union all
select ‘总销售价格‘,SUM(销售价格*销售数量) from MyOrder



---正确,对联合后进行排序
select 
	商品名称,
	sum(销售价格*销售数量) as 销售总价
from Myorder
group by 商品名称
union all
select ‘总销售价格‘,SUM(销售价格*销售数量) from MyOrder
order by 销售总价


---错误,对联合后进行排序
select 
	商品名称,
	sum(销售价格*销售数量) as 销售总价
from Myorder
group by 商品名称
order by 销售总价 -----------错误,有序了,就不是集合,不能和后面进行联合
union all
select ‘总销售价格‘,SUM(销售价格*销售数量) from MyOrder




select * from TblScore

--查询出成绩表中的数学:最高分,最低分,平均分

select 
	MAX(tMath) as 最高分,
	MIN(tMath) as 最低分,
	AVG(tMath) as 平均分
	
from TblScore

select 
	(select MAX(tMath)) as 最高分,
	(select min(tMath)) as 最低分,
	(select avg(tMath)) as 平均分
	
from TblScore


select ‘最高分‘ as 名称,分数=MAX(tMath) from TblScore 
union all
select ‘最低分‘ as 名称,分数=min(tMath) from TblScore 
union all
select ‘平均分‘ as 名称,分数=avg(tMath) from TblScore 



-------------使用union 向表中插入多条数据---

---备注:
select * from TblStudent

insert into TblStudent
select ‘美的‘,‘女‘,‘广东省佛山‘,40,‘1988-02-8‘,‘45163445155‘,5
union all
select ‘美的1‘,‘女‘,‘广东省佛山1‘,40,‘1981-02-8‘,‘45163445155‘,2
union all
select ‘美的2‘,‘女‘,‘广东省佛山2‘,40,‘1982-02-8‘,‘45163445155‘,3
union all
select ‘美的3‘,‘女‘,‘广东省佛山3‘,40,‘1983-02-8‘,‘45163445155‘,5

------------------------向表中插入多条记录------
-------------------备份表:把tblStudent进行备份tblStudent20170415backup
--将表结构和表的数据进行备份
--不能把原来表的约束进行复制进行备份
--只能执行一次,因为,每次执行都会创建表,但表已经存在,就会报错
select *  
into tblStudent20170415backup
from tblStudent

select *  from tblStudent20170415backup


---只备份表结构,不拷贝数据---
--写法1
select  top 0 *  
into tblStudent20170415backup2
from tblStudent

select *  from tblStudent20170415backup2



---只备份表结构,不拷贝数据---
--写法2--使用判断条件
select  *  
into tblStudent20170415backup3
from tblStudent
where 1<>1

select *  from tblStudent20170415backup3


----------------------对已经存在的表,进行添加数据
----------------------也就是追击数据---

select * from tblStudent20170415backup2

---把学生表中的女同学插入到里面

insert into tblStudent20170415backup2
select 
	tSName,tSGender,tSAddress,tSAge,tSBirthday,tSCardId,tSClassId
from  TblStudent
where tSGender=‘女‘



---第十七章 字符串函数

---常用的字符串函数
--1.len()计算字符的个数
print len(‘HI~最近‘)--5个

--datalength()返回所占字节的个数,这个不是字符串函数
print datalength(‘HI~最近‘)---7个


--2.upper(),lower()
print upper(‘abGad‘)
print lower(‘abGad‘)

--3.去掉两端空格

print(ltrim(rtrim(‘  hao123    ‘))+‘new‘)

--字符串截取

--4.1 left()
print left(‘珠海格力电器股份有限公司‘,5)
--4.2 right()
print right(‘珠海格力电器股份有限公司‘,5)

--4.3 substring() 截取字符串
print substring(‘珠海格力电器股份有限公司‘,2,3)

-----------------日期和时间函数
print convert(varchar(20),getdate(),120)
print sysdatetime()

--dateadd(),增加日期
print dateadd(day,360,getdate())
print dateadd(month,12,getdate())
print dateadd(year,1,getdate())

select *  from TblStudent
--查询出入职一年(含)以前的员工信息
select  * 
from TblStudent
where DATEADD(YEAR,1,tSBirthday)<=GETDATE()


--datediff()计算两个日期的差
select DATEDIFF(YEAR,‘1999-4-15‘,GETDATE())
select DATEDIFF(MONTH,‘1999-4-2‘,GETDATE())
select DATEDIFF(day,‘1999-4-2‘,GETDATE())

--统计出不同年份入职员工的个数


--请统计出入职n年的人的个数
--入职年数   人数
--1年		2人
--5年		12人

select 
	*,
	工龄= DATEDIFF(YEAR,tSBirthday,GETDATE())
from TblStudent 




select 
	工龄= DATEDIFF(YEAR,tSBirthday,GETDATE()),
	COUNT(*) 人数
from TblStudent 
group by DATEDIFF(YEAR,tSBirthday,GETDATE())



--获取日期的某个部分的值
--备注:方法1
print datepart(year,getdate())
print datepart(month,getdate())
print datepart(day,getdate())
print datepart(dayofyear,getdate())


--备注:方法2
print year(getdate())
print month(getdate())
print day(getdate())

--返回日期的某个部分,字符串表示形式
print datename(year,getdate())



---请统计不同年份入职的员工的个数

select 
	入职年份=YEAR(tSBirthday),
	人数=count(*)
	

from TblStudent
group by YEAR(tSBirthday)

select * from TblScore
select * from TblClass
insert into TblClass values(‘格力1期‘),(‘格力2期‘)

delete from TblClass where tClassId in (505,506)
update TblClass set tClassName=‘格力电器1期‘ where tClassId=503
select count(*) from TblClass


----第十八章 连接查询
--查询数据时,当需要将多个表中的列共同显示到一个结果集中的时候,可以使用连接查询
--笛卡尔积
create table phoneType
(
	ptId int,
	ptName varchar(20)
)

insert into phoneType
values(1,‘朋友‘),(2,‘同事‘),(3,‘同学‘),(4,‘家人‘)

create table phoneNum
(
	pId int,
	pTypeId int,
	pName varchar(20),
	pCellPhone varchar(20),
	pHomePhone varchar(20)

)

insert into phoneNum
values(1,1,‘刘备‘,‘13000000‘,‘700000‘),
(2,1,‘关羽‘,‘13000001‘,‘700001‘),
(3,1,‘张飞‘,‘13000002‘,‘700002‘),
(4,2,‘曹操‘,‘13000003‘,‘700003‘),
(5,2,‘大乔‘,‘13000004‘,‘700004‘),
(6,3,‘孙权‘,‘13000005‘,‘700005‘),
(7,3,‘小乔‘,‘13000006‘,‘700006‘)

select * from phoneType

select * from phoneNum

select 
pn.pId,pt.ptName,pn.pName,pn.pCellPhone,pn.pHomePhone 
from phoneType pt,phoneNum pn
where pt.ptId=pn.pTypeId

select 
pn.pId,pt.ptName,pn.pName,pn.pCellPhone,pn.pHomePhone 
from phoneNum pn inner join phoneType pt
on pt.ptId=pn.pTypeId

select * from phoneNum,phoneType

--没有重名的列,才可以直接用* 号代替
--要是有重名的列,则用表名.列
select *
from phoneType pt inner join phoneNum pn
on pt.ptId=pn.pTypeId

--多表连接,直接在后面加inner jion ...on...



--case的使用
--相当于if  else
create table [user]
(
	uId int  identity(1,1) primary key,
	name varchar(50),
	level int  --1骨灰 2大虾 3菜鸟
)

insert into [user](name,level)values(‘犀利哥‘,1),(‘小月月‘,2),(‘芙蓉姐姐‘,3)

select *,头衔=‘菜鸟‘ from [user]


--相当于if  else

--注意:then 后面的类型必须保持一致
select *,
		头衔=case
				when [level]=1 then ‘菜鸟‘
				when [level]=2 then ‘老鸟‘
				when [level]=3 then ‘大师‘
			end 

from [user]

--相当于switch--只能等值进行判断
select *,
		头衔=case [level]
				when 1 then ‘菜鸟‘
				when 2 then ‘老鸟‘
				when 3 then ‘大师‘ 
				else  ‘骨灰级‘
			end 

from [user]


select * from TblScore
select 
	tScoreId,
	tSid,
	tEnglish
	
from TblScore


--对成绩进行划分等级
select 
	tScoreId,
	tSid,
	tEnglish,
	等级=case
			when tEnglish>=85 then ‘优秀‘
			when tEnglish>=45 then ‘及格‘
			when tEnglish<45 then ‘不合格‘
	
		end
from TblScore



create table TestA
(
	A int,
	B int,
	C int
)

insert into TestA values(10,20,30),(20,30,10),(10,20,30),(10,20,30),(20,30,10),(10,20,30),(10,20,30),(20,30,10),(10,20,30),(10,20,30),(20,30,10),(10,20,30)
select * from TestA


--第十九章 索引
--1.索引的目的:提高查询效率
--2.索引分两种
--2.1聚集索引(物理)索引和物理(实际)是一样的。一个表中只能有一个聚集索引
--2.2非聚集索引(逻辑)一个表中可以有多个非聚集索引
--3.增加索引后,会增加额外的存储空间。同时降低了增加新纪录,修改、删除的效率。
--备注:索引意味着排序,排序后则可高效的查询

select A from TestA where A>10 order by A asc

--建立索引  聚集索引,在经常用到查询的列建立索引
create clustered index index_A on TestA(A)

--删除索引
drop index TestA.index_A


--查询比较慢
--因为B没有建立索引
--A建立索引,但是B没有
select A,B from TestA where B>10 order by B asc


--给B创建非聚集索引
create nonclustered index index_B on TestA(B)

--删除索引
drop index TestA.index_B

--备注:在使用的列进行建立索引
--不要给每个列都建立索引,在需要查询的列建立索引


--效率低,想建立索引,但是不会建立索引,则点击[工具]---数据库引擎优化顾问


CREATE NONCLUSTERED INDEX [_dta_index_TestA_6_18099105__K1] ON [dbo].[TestA] 
(
	[A] ASC
)WITH (SORT_IN_TEMPDB = OFF, IGNORE_DUP_KEY = OFF, DROP_EXISTING = OFF, ONLINE = OFF) ON [PRIMARY]

CREATE NONCLUSTERED INDEX [_dta_index_TestA_6_18099105__K2_1] ON [dbo].[TestA] 
(
	[B] ASC
)
INCLUDE ( [A]) WITH (SORT_IN_TEMPDB = OFF, IGNORE_DUP_KEY = OFF, DROP_EXISTING = OFF, ONLINE = OFF) ON [PRIMARY]


--备注:当你建立主键的时候,自动给建立索引


--二十 子查询 select * from ((select col1,col2) from table1)  as t
--独立字查询
--相关子查询

select aa.A from (select A,B from TestA) as aa

--独立子查询的格式
--select * from tableA where tAId=
--(select tAId from tableB where tname=‘格力‘)


--相关子查询的格式
--select * from tableA  as tA where
--exists(select * from tableB  as tB where tA.tAId=tB.tBId and tname=‘格力‘)



--分页查询,要先进行排序
select * from TestA

--每页显示10条数据
--第一页显示10条
--第二页
--.............
select top 10 * from TestA order by A desc

--查询前两页的数据
select top (10*2) * from TestA order by A desc

--查询第二页的数据


CREATE TABLE [dbo].[TestB](
	[A] [int] NULL,
	[B] [int] NULL,
	[C] [int] NULL,
	[ID] int identity(1,1) primary key
)

insert into [TestB] select * from TestA

select * from TestB


select top 10 *  from TestB where ID not in(
select top (10*(2-1)) aa.ID from TestB  aa order by A desc)  order by A desc


--联合是把行进行连接
--连接时吧列进行连接
--连接的作用:多表查询
--左外连接
--lelf outer jion 
--简化:left jion

--当使用连接查询的时候,如果同时要指定查询的条件,那么一定要使用where语句
--不要直接在on条件后面跟and来编写其他查询条件

--select * from A left jion B on ..where...


--视图
--视图只是对查询语句的封装,里面并没有数据
--真正的数据,还是存在表中的


--二十一、视图
*/
--创建视图
go
create view vw_name
as 
select B,C,ID 
from TestB
where ID>100
go
select * from vw_name

/*
--在创建数据库视图时遇到这种一种语法错误“create view必须是批处理中仅有的语句”,解决方案如下:
 --   因为create view 必须是批处理中的第一条语句。也就是说,你可能在这段代码之前还有其他的语句是同时处理的,为此,你可以在这段代码的前一行加上GO,在这段代码结束后一行加上GO就可以了。。或者你把这段代码单独执行就不会出错了。
  -- 附上示例代码如下:
   --    出错的语句:

use student_data
go
create view V_S_C_G as
select Student.Sno,Sname,Course.Cno,Cname,Student_Course.grade
from Student_Course,Student,Course
where Student.Sno = Student_Course.Sno and Course.Cno = Student_Course.Cno
select * from V_S_C_G


        修改后的语句:
use student_data
go
create view V_S_C_G as
select Student.Sno,Sname,Course.Cno,Cname,Student_Course.grade
from Student_Course,Student,Course
where Student.Sno = Student_Course.Sno and Course.Cno = Student_Course.Cno
go
select * from V_S_C_G
*/

--视图中有相同的列名时,必须使用别名,这样可以避免在视图中存在两个名字完全一样的名字,这样会报错的
--视图中不能使用order by进行排序。因为视图中的数据是集合

--不能把有序的数据,因为不是结果集,所以也不能加入到视图
--不能在视图里面进行排序
--但是可以在视图查询的时候进行排序

--二十二、存储过程


--二十三、T-sql的使用--编程

--1.声明变量
declare @name nvarchar(50)
declare @age int

--简化:声明变量简化
--declare @name nvarchar(50),@age int

--2.为变量复制
--2.1方法1:复制
set @name=‘格力‘

--2.2方法2:复制
select @age=18

--3.打印输出
select ‘姓名‘,@name
select ‘年龄‘,@age

--错误写法,
--print ‘姓名‘,@name

--正确写法,
select ‘姓名‘,@name
/*
--sql 是没有for循环,但是可以用while进行循环
--输出100次

declare @i int=1 --声明变量的时候,同时进行复制
while @i<=5
begin
	print ‘hello‘
	set @i +=1
end

--计算1---100的和
declare @i int=1,@sum int=0 --声明变量的时候,同时进行复制
--sum必须赋值
while @i<=100
begin
	set @sum +=@i
	set @i +=1
end
print @sum

--条件--if else 的使用
declare @n int =10
if @n>10
begin
	print ‘@n>10‘
end
else if @n>5
begin
	print ‘5<@n<=10‘
end
else
begin
	print ‘@<=5‘
end
*/
--计算1--100所有的奇数的和
declare @i int=1,@sumji int =0
while @i<=100
begin
	set @sumji +=@i
	set @i+=2
end
select ‘奇数和:‘ ,@sumji

/*
--计算1--100所有的偶数的和
declare @i int=2,@sumou int =0
while @i<=100
begin
	set @sumou +=@i
	set @i+=2
end
select ‘偶数和:‘ ,@sumou

*/

print @@version --系统变量:一般两个@@为系统变量

set @@version=‘gbk‘
print @@error
print @@language
print @@MAX_CONNECTIONS
PRINT @@SERVERNAME

--二十三、事务

create table bank
(
	cId nvarchar(20),
	balance int 
)

insert into bank
values(‘0001‘,910),(‘0002‘,100)

select * from bank
--‘0002‘建立了约束条件,必须balance大于10
update bank set balance=balance-100 where cId=‘0002‘
update bank set balance=balance+100 where cId=‘0001‘

--那怎么保证两个sql语句同时成功或者同时失败你呢?
--通过事务进行转账
--1.打开一个事务
begin transaction
declare @sum int=0
	update bank set balance=balance-10 where cId=‘0002‘
	set @sum+=@@ERROR
	update bank set balance=balance+10 where cId=‘0001‘
	set @sum+=@@ERROR
--只要任何一条sql语句执行出错,那么最后的@sum就不是0
	if @sum<>0 --表示程序出现错误
	begin
	--回滚
		rollback
	end
	else  --表示没有出错
	begin
	--提交,一旦提交就不能回滚
	--没提交之前就可以回滚
		commit
	end
	
--事务的分类
--1自动提交事务:全部自动

--2隐式事务:自动打开,但是需要手动提交事务或者滚回事务
--set implicit_transactions {on |off}
set implicit_transactions on --打开一个隐式事务

set implicit_transactions off --关闭隐式事务
--显示事务:需要手动打开事务,手动提交事务或者滚回事务





	
	
	

  

sql-server笔记V20170429

标签:rollback   添加   sda   向上取整   gad   cap   示例   身份证   表示范围   

原文地址:http://www.cnblogs.com/hnwcan/p/6786560.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!