数据库

drop database myschool

---------------------------------创建数据库------------------------------------
create database MySchool
on
(
    name='MySchool',
    filename='c:\database\MySchool.mdf',
    size=3,
    filegrowth=1,
    maxsize=100
)
log on
(
    name='MySchool_Log',
    filename='c:\database\MySchool.ldf',
    size=3,
    filegrowth=10%,
    maxsize=100
)
go
--修改
--alter database

--创建表
--drop table [table]

---------------------------------切换数据库------------------------------------
use MySchool
go
---------------------------------创建表---------------------------------------
create table [Class]
(
    [cId] int identity(1,1) primary key,
    [cName] nvarchar(10) not null,
    [cDescription] nvarchar(200)
)
go
--decimal(18,0) 
--18是定点精度,有效位数;0是小数位数。

create table [Student]
(
    [sId] int identity(1,1)primary key,
    [sName] nvarchar(10) not null,
    [sAge] int null,
    [sNo] decimal(18,0),
    [sBirthday] datetime,
    [sClassId] int not null
)
go
--修改表 增加列
alter table [Student]
add sSex nchar(1) 


--DDL数据库定义语言,上面的创建数据库,创建表,是DDL
--DML数据库操作语言,增删改查
---------------------------------插入数据------------------------------------

insert into [Class]([cName],[cDescription]) values('高一一班','快班')

--简写
insert [Class] values('高一二班','中班')

insert into [Class]([cName])values('高一三班')

select *from student

--日期必须加单引号
insert into [Student](sSex, sName, sAge, sNo, sBirthday, sClassId)
values('','张三',18,122222222,'1982-1-1',1)
insert into [Student](sSex, sName, sAge, sNo, sBirthday, sClassId)
values('','李四',18,122222222,'1982-1-1',1)
insert into [Student](sSex, sName, sAge, sNo, sBirthday, sClassId)
values('','王五',18,122222222,'1982-1-1',1)

---------------------------------更新数据------------------------------------
update student set sSex=''
update student set sSex='',sAge=20

update student set sClassId=3 where sName='王五'

update student set sclassid=10 where sAge=50 or (sage>=19 and sage<=20)

update student set sage=sage+1 

select *from score

update score set english =english/2
---------------------------------删除数据------------------------------------
--delete删除时存入日志
delete from student

delete from student where sName='张飞'
-------------------------------truncate清空表,不存入日志,清空自动编号------------------------
truncate table student

insert into Class (cName,cDescription) values ('高一一班','快班')
insert into Class (cName,cDescription) values ('高一二班','中班')
insert into Class (cName,cDescription) values ('高一三班','慢班')
insert into Class (cName,cDescription) values ('高二一班','快班')
insert into Class (cName,cDescription) values ('高二二班','中班')
insert into Class (cName,cDescription) values ('高二三班','慢班')

insert into Student (sClassId,sName,sAge,sSex,sNo,sBirthday) values (1,'刘备',20,'',123456789012345678,'1987-5-6')
insert into Student (sClassId,sName,sAge,sSex,sNo,sBirthday) values (1,'关羽',19,'',123456789012345671,'1988-8-6')
insert into Student (sClassId,sName,sAge,sSex,sNo,sBirthday) values (1,'张飞',18,'',123456789012345672,'1989-5-19')
insert into Student (sClassId,sName,sAge,sSex,sNo,sBirthday) values (4,'曹操',22,'',123456789012345673,'1985-12-6')
insert into Student (sClassId,sName,sAge,sSex,sNo,sBirthday) values (4,'夏侯惇',22,'',123456789012345674,'1985-3-6')
insert into Student (sClassId,sName,sAge,sSex,sNo,sBirthday) values (4,'华佗',50,'',12345678901234565,'1957-1-16')
insert into Student (sClassId,sName,sAge,sSex,sNo,sBirthday) values (4,'甄姬',18,'',12345678901234565,'1989-8-8')

insert into Score (studentId,english) values(1,90)
insert into Score (studentId,english) values(2,90)
insert into Score (studentId,english) values(3,59)
insert into Score (studentId,english) values(4,100)
insert into Score (studentId,english) values(5,60)
insert into Score (studentId,english) values(6,0)
insert into Score (studentId,english) values(7,80)

select *from student

create table [Score]
(
    studentId int not null primary key,
    english float
)
go


alter table score 
add math float null

alter table score 
add sId int identity(1,1) primary key

-------删除主键
Declare @Pk varChar(100);
Select @Pk=Name from sysobjects where Parent_Obj=OBJECT_ID('Score') and xtype='PK';
if @Pk is not null
exec('Alter table Score Drop '+ @Pk)


update score set english=english+10 
where studentId=(select sId from Student where sName='刘备') 

select *from score

update score set english=english+5 
update student set sage=sage-1 where sSex=''
select *from student
Select
--简单查询

select *from student
select sId, sName, sAge, sNo, sBirthday, sClassId, sSex, sInTeam from student
select sname from student

--给列改名
select sname as '姓名' ,sSex as '性别' from student
select sname '姓名' ,sSex '性别' from student
select '姓名'=sname ,'性别'=sSex from student

select sname as '姓名' ,sSex as '性别' ,sAge as '年龄'
from student where sSex=''

select sname as '姓名' ,ssex as '性别',sage as '年龄' 
from student where sage>20

select 2*3
select getdate()

--Top Distinct
select top 2 * from student
order by sage

--百分之10个学生,如果有小数位数,直接进1
select top 10 percent  * from student 

select *from student where sname='张飞'
--去掉重复的项
select distinct sname from student
select distinct sName,sAge,sSex from student
select *from student

--聚合函数max min avg sum count

select max(english) from score
select min(english) from score
--null值是不参加avg的运算
select avg(english) from score

select max(english),min(english),avg(english)from score

select sum(english)/count(*)from score

select sum(english) from score
select count(*)from student
--尽量写列明,因为*的运行速度要慢些
select count(sName)from student

--带条件查询
select studentid from score where english>60
select studentId,sname,english from score, student where (student.sid=score.studentid) and english>60
select english from score where studentid=7
select sname from student where sid=7 
select *from student

--between..... and .....
select sAge,sSex,sName from student
where sAge between 20 and 30 and sSex=''

select *from student 
where sBirthday between '1987-01-01' and '1989-12-12'

--in(1,2,3,4).....
select *from student
where sClassId=1 or sClassId=3 or sClassId=4

select *from student 
where sClassId in(1,2,3,4)

--模糊查询
select left('123',1)
select *from student where left(sName,1)=''
select *from student where sName like '%亮%'
select *from student where sName like '张_'
select *from student where sName like '张__'
select *from student where sName like '张[飞亮]'

alter table student
add sPhone nchar(6)

alter table student 
add constraint CK_Student_sPhone check (sPhone like '[0-9][0-9][0-9][0-9][0-9][0-9]')

insert into student  (sClassId,sName,sAge,sSex,sNo,sBirthday,sPhone) values (1,'刘备',20,'',123456789042345678,'1987-5-6',123)
delete from student where sNo=123456789042345678 

--null
select null+123
select *from student where sPhone is null
select *from score where english is null
select *from score where english is not null

--order by 放最后面 默认是asc 
 select top 2 *from student 
 order by sName
select *from student order by sAge desc

--english 成绩相同时,按math的降序来排列
select *from score order by english ,math desc

select *from student where sSex='' order by sAge desc

--group by 
--每个班有多少个学生
select count(*) ,sClassid from student 
group by sClassid

--每个班男同学的个数
select count(*) as '个数' ,sClassId from student 
where sSex=''
group by sClassId 

--每个班平均年龄超过25岁的哪些班
--where是分组前进行筛选,having是分组后进行筛选,where中不能使用聚合函数
select count(*), sClassId ,avg(sage) from student 
group by sClassId
having avg(sAge)>24

--求人数超过5个的那些班
--先求"每个"班的人数,再按人数>5进行筛选
select sclassId as '班级' ,count(*)as '人数' from student 
group by sClassId
having count(*)>5

--男生女生分别多少人
select sSex, count(*) from student 
group by ssex

--求每个班有多少个男生

select sClassId, count(sSex) from (select *from student where sSex='')as a
group by sclassid 

select sclassid,count(*)from student 
where sSex=''
group by sclassid

--每个班中男同学的平均年龄
select sClassId, avg(sage) from (select *from student where sSex='')as a
group by sclassid 

select sclassid ,avg(sage)from student 
where ssex=''
group by sclassid

--求平均年龄小于24的那些班
select sclassid ,avg(sage) from student
group by sclassid
having avg(sage)<24

--union  合并两个查询结果集
--要求:列的个数一致,类型一致
--union帮我们按字母排序,去除重复数据
select sName,sSex from student union
select tName,tsex from teacher

select sName ,sSex,sClassId from student union
select tName,tsex, -1 from teacher

--union all 做报表
--直接连接两个结果集

select sName,sSex from student union all
select tName,tsex from teacher

--要求在一个表格中查询出学生的英语最高成绩,最低成绩,平均成绩
select min(english) as '最低成绩',max(english)as '最高成绩',avg(english)as '平均成绩' from score
 
select '最低成绩', min(english) from score union all
select '最高成绩', max(english) from score union all
select '平均成绩', avg(english) from score

--查询每位老师的信息,包括姓名、工资,并且在最后加上平均工资和
select tName,tSalary from teacher union all
select '平均工资',avg(tsalary) from teacher union all
select '最高工资',max(tsalary) from teacher

--使用union一次插入多条数据
insert into Score(studentId,english,math)
select 1,80,100 union
select 2,60,80 union
select 3,50,59 union
select 4,66,89 union
select 5,59,100 

--把现有表中的数据插入到新表中(newStudent表不能存在),不插入主键
select *into newStudent from student

-- 把现有表中的数据复制到一个已存在的表

insert into newStudent select sName, sAge, sNo, sBirthday, sClassId, sSex, sInTeam, sPhone from student
函数
--------------------------len截取字符串长度
select len('123')
 select len(sName) as '姓名字数' ,sname from student
select lower('safFG')
select upper('asdf23')

select '   abc   '
select ltrim('   abc    ')
select rtrim('   abc    ')+'123'
select ltrim(rtrim('     abc         '))


select left('张三',1)
 -ip12325446
select right('ip12325446',len('ip12325446')-2)

--起始位置从1开始
select substring('ip12325446',1,2)

--查询班级内所有学生的姓
select distinct left(sName,1)from student

--日期函数
select getdate()

select dateadd(day,3,getdate())
select dateadd(month,-1,getdate())
select dateadd(year,1,getdate())
--加一个季度
select dateadd(quarter ,1,getdate())
select dateadd(week,1,getdate())

select year(getdate())
select month(getdate())
select day(getdate())

--当前月份的销售记录,要加年,否则取出来的总的这个月的销售记录了
select *from xsjl
where month(xsjl.date)=month(getdate()) and year(getdate())=year(xsjl.date)

--后面减去前面的
select datediff(day,getdate(),'2012-12-24')
select datediff(second,getdate(),'2012-12-24')
select datediff()

--统计不同生日年份的学生个数
select year(sbirthday) as '年份' ,count(*)as '人数' from student 
group by year(sbirthday) 

--求每个年龄有多少个学生
select datediff(year,sbirthday,getdate()),count(*) from student 
group by datediff(year,sbirthday,getdate())

select datename(year,getdate())--字符串
select datepart(year,getdate())--整数
--今天的一年的第几天
select datename(dayofyear,getdate())
select datename(week,getdate())

select datename(weekday,getdate())
select datepart(weekday,getdate()) 

--转换

select cast(30.56 as varchar(5))

select cast(right(sno,3)as int) from student
select right(sno,3) from student

select cast(45465.123 as decimal(10,2))
--平均成绩保留2为小数
select cast(avg(english)  as decimal(10,2)) from score

--不四舍五入
select cast(89.6 as int)
--四舍五入
select cast(round(89.6,0) as int)

--convert
select convert(int ,89.4645)

select convert(decimal(10,2),avg(english)) from score

select convert (varchar(30), getdate(),21)
select convert (varchar(30), getdate(),20)
--2012-12-17
select convert(varchar(10),getdate(),20)
--15:06:49
select convert(varchar(10),getdate(),108)

--有没参加考试的,但算平均成绩时还是要算上
--avg不包括null
select avg(english) from score

select sum(english)/count(sId) from score
--isnull(),如果为null转换成0
select cast(avg(isnull(english,0)) as decimal(10,2)) from score
原文地址:https://www.cnblogs.com/hejinyang/p/2818799.html