注意:
select top 3 Name,Age,Gender from view_Student where group having order by id desc
5 6 7 7 7 1 1 2 3 4 8 8 8
在最终生成用户想要的数据之后,才进行排序,如果不得不排序,那么就尽可能把消耗减到最小。
系统变量
error 记录的是最后一个出现错误的地方的错误号(消息后面的数字)
事务里面必须用到这个error。
IF()ELSE()
条件表达式里面,可以使用一个只有一行一列的查询作为判断的一个根据 IF( (SELECT COUNT(id) FROM dbo.Student) >10) BEGIN PRINT '好多人啊' END ELSE begin PRINT '人好少啊' END
触发器
触发器最难的是在与根据业务需求,写出触发器里面需要执行的sql语句。
触发器本生并不难。
After 和for 都是在增删改执行的时候执行另外的sql语句。
Instead of 是,取代原来的操作。
--创建一个新增触发器 CREATE TRIGGER tgforClassesOnInsert ON Classes AFTER INSERT as begin PRINT '新增了一行数据' --INSERT INTO log (操作的表,执行时间,哪个用户) END --创建一个删除触发器 CREATE TRIGGER tgforClassesOnDelete ON Classes AFTER DELETE as begin PRINT '删除了一行数据' END --创建一个修改触发器 CREATE TRIGGER tgForClassesOnUpdate ON Classes AFTER UPDATE as begin PRINT '修改了一行数据' END --*********FOR CREATE TRIGGER tgclassupdate ON classes FOR update as begin PRINT 'for的更新' END CREATE TRIGGER tgclassinsert ON classes FOR INSERT as begin PRINT 'for的插入' END CREATE TRIGGER tgclassdelete ON classes FOR DELETE as begin PRINT 'for的删除' END
--************instead OF CREATE TRIGGER tgclassesIinsert ON classes instead OF INSERT as begin PRINT 'instead ++ INSERT' END CREATE TRIGGER tgclassesIupdate ON classes instead OF update as begin PRINT 'instead ++ update' END CREATE TRIGGER tgclassesIdelete ON classes instead OF delete as begin PRINT 'instead ++ delete' END
事务
储存过程
--大部分学生不及格,提分,直到一半学生及格为止 if exists(select * from sysobjects where [name]='usp_upGrade') drop proc usp_upGrade go create proc usp_upGrade as begin declare @count int --记录总人数 set @count = (select count(*) from score) while @count/2 < (select count(*) from score where english<60) begin update score set english= english+ 2 end update score set english = 100 where english> 100 end go
--带输入参数的存储过程 --题出难了,降低及格分数线 if exists(select * from sysobjects where [name]='usp_upGrade1') drop proc usp_upGrade1 go create proc usp_upGrade1 @pass float = 60 as begin declare @count int --记录总人数 set @count = (select count(*) from score) while @count/2 < (select count(*) from score where english<@pass) begin update gradeInfo set grade = grade + 2 end update score set english = 100 where english> 100 end exec usp_upGrade1 80
--输出参数 if exists(select * from sysobjects where [name]='usp_upGrade2') drop proc usp_upGrade2 go create proc usp_upGrade2 @num int output,@pass float = 60 as begin set @num = 0 declare @count int --记录总人数 set @count = (select count(*) from gradeInfo) while @count/2 >= (select count(*) from gradeInfo where grade>=@pass) begin set @num = @num + 1 update gradeInfo set grade = grade + 2 end update gradeInfo set grade = 100 where grade > 100 end