SQL语句总结

-------------------------新建数据库-------------------------------

create database stuDB

on primary

(

name='stuDB_data',

filename='D:数据库stuDB_data.mdf',

size=5mb,

maxsize=100mb,

filegrowth=15%

)

log on

(

name='stuDB_log',

filename='D:数据库stuDB_log.idf',

size=2mb,

filegrowth=1mb

)

go

--------------------------新建表stuinfo------------------------------------

use stuDB

go

create table stuinfo

(

stuName varchar(20) not null,

stuNo char(6) not null,

stuAge int not null,

stuID numeric(18,0),

stuAddress text

)

go

--------------------------新建表stumarks-------------------------------------------------

create table stumarks

(

stuNo char(6) not null,

stuWritten int not null,

stuMachine int not null

)

Go

====================语句约束================================

===========================================================

-----------------------------主键约束-------------------------------------

Alter(改) table stuinfo

add  constraint(约束) PK_stuNo primary key(stuNo)

------------------------------唯一约束-------------------------------------

alter table stuinfo

add constraint UQ_stuID unique(stuID)

-------------------------------检查约束------------------------------------

alter table stuinfo

add constraint CK_stuAge check(stuAge between 15 and 40)

-------------------------------默认约束------------------------------------

alter table stuinfo

add constraint DF_stuAddress default'地址不详' for stuAddress

-------------------------------外键约束------------------------------------

alter table stumarks

add constraint FK_stuNo foreign key(stuNo) references (指向)stuinfo(stuNo)

Go

========================================================

---------------------------------数据操作语言--------------------------------------------

========================================================

use stuDB

select *from stuinfo 

insert into stuinfo values ('小红','004',23,12345,default)--增加一行

insert into stuinfo  (stuName,stuNo ,stuAge ,stuID ,stuAddress ,sex )values('四风','005',23,'12347','济南','')-----------增加一行

update stuinfo set stuAddress ='如皋' where stuNo =004--修改

delete  from stuinfo where stuNo =004--删除一行

create table student----------新建表

(

stuName varchar(20) null,

stuNo char(6) null,

stuAge int null,

stuID numeric(18, 0) null,

stuAddress text null

)

select * from student 

insert into student (stuName,stuNo,stuAge,stuID,stuAddress)

 select stuName,stuNo,stuAge,stuID,stuAddress from stuinfo----插入多行(类似复制,需提前建表)

 delete from student where stuNo =1---------------删除学号为的学生

 delete from student -------------删除student整张表(一行一行删除),但表结构还在(不删除标识列)

 drop table student------------删除student整张表

 select * into students from stuinfo ---------------复制表stuinfostudents中,不用提前建表

 select * from students

 truncate table students-----------------删除表,一下子释放存储空间,标识列从初始开始,表结构还在

 drop table students----------------删除整张表,表结构

select * from tel

 select * from tel group by code having COUNT(code)>1-------------查找tel表中code列重复的行

 select * from stuinfo 

 //select  '性别' as sex from stuinfo ----------虚拟表中添加列sex

alter table stuinfo add sexi char-------------增加一列

alter table stuinfo drop column sexi -----------------删除一列

========================select查询语句=====================================

use stuDB 

select * from stuinfo  

select * from stumarks 

alter table stuinfo add sex char-----------插入一行sex

insert into stuinfo  (stuName,stuNo ,stuAge ,stuID ,stuAddress ,sex )values('四风','005',23,'12347','济南','')------插入一行

update stuinfo set sex='' where stuNo =001----------修改性别

update stuinfo set sex=''where stuNo=002

update stuinfo set sex=''where stuNo=003

select * from stuinfo where sex=''----------查找男学员

select * from stumarks where stuWritten between 75 and 100----------查找笔试成绩优秀学员

select SUM(stuwritten) as 笔试总成绩,SUM (stuMachine ) as 机试总成绩 from stumarks -------------统计笔试总成绩,机试总成绩

select  count(stuNo) as 学员人数,avg(stuwritten) as 笔试平均分,avg(stuMachine) as 机试平均分 from stumarks ----------统计本次参加人数,笔试平均分,机试平均分

select stuNo as 没有通过的人 from stumarks where stuWritten <60 or stuMachine <60---------查找考试没有通过的人

select stuNo as 学号,stuwritten as 笔试成绩,stuMachine as 机试成绩 from stumarks ----------查询并显示学员学号,笔试成绩,机试成绩

update stumarks  set stuwritten=stuWritten +5,stuMachine=stuMachine +5 

update stumarks  set stuMachine=100 where   stuMachine>100 

update stumarks set  stuWritten =100 where stuWritten >100

select * from stumarks ---------------要求每个学生加分,最高分为100

======================两表之间关联========================================

select users.userName ,users.userId ,account .score ---------

from users left join account --------------------------------

on users.userId =account.userId ------------=========-多表联结(左外关联得左表的全部和右表匹配的号)

select * from users left join account  on users.userId=account .userId 

select users .*,account .* from users left join account  on users.userId=account .userId 

insert into account (users.userId ,score )

select users.userId ,'2'from users left join account on users.userId =account .userId 

where account .score is null------------查找account中无记录的人并插入信息

=======================作业练习=====================================

已知有如下三个表

  S (sno,sname) 学生表。SNO 为学号,SNAME 为姓名 

  C (cno,cname,cteacher) 课程表。cno 为课程号,cname为课程名,cteacher为任课教师 

SC(sno,cno,score) 选课表,记录学员选修的课程与成绩。sno为学号(S表中sno的外键)cno为课程号(C表中cno的外键), score为成绩

use stuDB 

select * from S

select * from C

select * from SC

alter table sc

add constraint FK_sno foreign key(sno) references s(sno)

alter table sc

add constraint fk_cno foreign key(cno) references c(cno)

问题一:列出所有选过课程学员的学号、姓名、所选课程名称、成

绩、任课老师

select S.sno,S.sname,C.cname,C.cteacher,SC.score from SC 

left join S on S.sno=SC.sno 

left join C on SC.cno=C.cno 

问题2:列出所有选修"基础会计学"的学员学号、姓名

select sno,sname from s where sno in

(select sc.sno from sc left join c on sc.cno=c.cno where 

c.cname='基础会计学')

问题3:找出成绩不合格的学员,列出其学号、姓名、不合格课程

名称、分数、任课老师

select S.sno,S.sname,C.cname,C.cteacher,SC.score from SC 

left join S on S.sno=SC.sno 

left join C on SC.cno=C.cno where sc.score<60

问题4:找出有一门或多门成绩不合格的学员,并将其所有参考课

程名称、任课老师、姓名、成绩

按成绩从低到高的顺序列出

select S.sname,C.cname,C.cteacher,SC.score from SC left 

join S on S.sno=SC.sno 

left join C on SC.cno=C.cno where sc.score<60 order by 

sc.score asc

问题5:找出同时选修课程号为"C1"和"C2"的学员姓名

select sname from s where sno in

(select sno from sc  where  cno='c1')

(select sno from sc  where  cno='c2')

问题6:列出没有选修过“李明”老师讲授课程的所有学生姓名

select sname from s where sno in 

(select sc.sno from sc left join c on sc.cno=c.cno where 

c.cteacher='李明')

问题7:列出有二门以上(含两门)不及格课程的学生姓名及其平均

成绩

select s.sname ,avg(convert(int,sc.score)) from s left join 

sc on s.sno=sc.sno group by s.sname having count(sname)>2

问题8:列出所有学生的姓名及平均成绩

select s.sname ,avg(convert(int,sc.score)) from s left join 

sc on s.sno=sc.sno group by s.sname 

====================视图作业========================================

use stuDB 

alter table stumark

add constraint FK_stuno foreign key (stuno) references student(stuno)

select * from student 

select* from stumark 

create view student_stumark

as

(select stuname  as '姓名',student .stuno  as '学号',笔试成绩

=case

    when writtenexam IS NULL then '缺考' 

    else writtenexam 

end 

,机试成绩

=case 

     when labexam  IS null then '缺考'

     else labexam

end,

是否通过=case

when writtenexam<60 or labexam<60 or writtenexam IS NULL  or labexam is null then '0'

else '1'

end

from student left join stumark on student .stuno =stumark .stuno) ------------中间表

select * from student_stumark--------------查询视图表

select count(student.stuno ) as '应到人数',count(examno) as '实到人数',

缺考人数= count(student.stuno )-count(examno)

from student left join stumark on student.stuno =stumark.stuno ---------------上面表

select count(*) as '总人数',sum(convert(int,是否通过)) as '通过人数',

convert(varchar(20),(sum(convert(int,是否通过))*100/count(*)))+'%' as 通过率

from student_stumark-------------最后一个表

============================视图、事务、存储过程=================

===============================================================

create table card--创建card

(

id varchar(10) primary key,--卡号

userName varchar(10) not null,--用户姓名

balance money not null--用户余额

)

drop table account

create table account--创建account

(

id int primary key identity,--交易编号

cardId varchar(10) not null,--卡号

tradeType char(1) ,--交易类型

number money --操作的金额

)

---------------添加约束----------------

alter table card drop constraint CK_balance

alter table card -- 检查约束,card 表中balance

add constraint CK_balance

check(balance>0)

alter table account drop constraint FK_cardId

alter table account--外键约束,两个 表中的cardId

add constraint Fk_cardId

foreign key(cardId) REFERENCES card(id)

--------------------card表中添加信息---------------------

insert into card(id,userName,balance) values('C001','张三',1235)

select * from card

-------------------account表中添加数据-------------------------

insert into account(cardId,tradeType,number)values('C001','0',100)

insert into account(cardId,tradeType,number)values('C011','0',100)

--delete from account

select * from account

----1、创建银行卡信息视图(字段都为中文)

go

create view view_card

as

select id as 卡号, userName as 用户姓名,balance as 余额 from card 

select * from view_card

---2、交易信息表视图,含卡号,用户姓名,交易类型,交易金额,现有余额等字段

go

create view view_card_account

as

select card.id as 卡号,userName as 用户姓名,tradeType as 交易类型,number as 交易金额,

balance as 现有余额 from account

inner join card on card.id = cardId

select * from view_card_account

go

--3、创建存钱或取钱的存储过程;接收两个参数,第一个为交易类型,第二个为交易金额

create proc proc_account

@cardId nvarchar(10),

@tradetype int,

@number money

as 

declare @balance int

 if(@tradetype=1) 

 begin

  select @balance=balance from card where id=@cardId

  update card set balance=@number+@balance where id=@cardId

  end

  else

  begin

  select @balance= balance from card where id=@cardId

   if(@balance<=@number)

     begin

       raiserror ('您的余额不够',12,5)

       return

     end

   update card set balance=balance-@number where id=@cardId

  end

  go

  go

  exec proc_account C001,1,500

  exec proc_account C001,0,400

  select *from card

--4、创建开户存储过程;接收三个参数,分别为卡号,用户姓名和开卡金额,可向card表添加一条记录

create proc proc_insert

 @cardId nvarchar(10),

 @userName nvarchar(10),

 @number money

 as

 if(@number<=0)

 begin

  raiserror ('不符合要求',10,6)

       return

 end

 else

 begin

  insert into card(id,userName,balance) values(@cardId,@userName,@number)

 end

 exec proc_insert C012,hhhh,12.10

 select * from card

--5、创建转账事务存储过程 接收三个参数,分别为转出卡号,转入卡号,转账金额。要求用事务控制。

create  proc proc_inout

  @incardId varchar(10),

  @outcardId varchar(10),

  @number money

  as

  declare @inputcard money,

  @outputcard money

  select @inputcard=balance from card where id=@incardId

  if(@inputcard<@number)

  begin

     raiserror ('钱不够',16,1)

       return

  end

  else

  begin

  select @outputcard =balance from card where id=@outcardId

   update card set balance=@inputcard-@number where id=@incardId

   update card set balance=@outputcard+@number where id=@outcardId

  end

  exec proc_inout C001,C002,100

  

   select *from card

===========================自定义函数==============================

stuInfo表中操作

创建自定义函数实现模糊查询,指定字符串初始部分,只要查询的结果是以指定字符串开头,都可查询出来

自己给stuInfo表添加一个字段province,代表学生所在省份,写SQL语句实现如下结果:

   

create function stuin(@code nvarchar(10))

returns table---返回一个表即不用转换类型

as

return (select stuName,score from stuinfo

where stuName like @code+'%')

select * from stuin('R')

原文地址:https://www.cnblogs.com/xiaomayizoe/p/5034732.html