-- 创建索引 if exists (select name from sysindexes where name ='IX_BANK') drop index bank.IX_BANK GO createunique index IX_BANK on Bank(name)
--删除索引 drop index bank.IX_BANK
-- 使用索引 select*from bank with(index = IX_BANK) where name like'%北京%' select*from bank where name like'%北京%'
--上机练习9_1 --在学生成绩表Score的score列创建索引,并使用索引查询成绩在90分以上的学生姓名和成绩。 if exists (select name from sysindexes where name ='IX_score') drop index bank.IX_score create index IX_score on score(score) GO select sd.name, s.score from student sd, Score s where s.score >90and sd.studentid = s.studentid
课上写的东西
1 2 3 4 5 6 7 8 9 10 11 12 13
createunique index ix_name on student(name)
select*from sysindexes
createfunction getScore() returnstable return select name, subjectname, score from student stu, subject sub, score s where stu.studentid = s.StudentID and s.SubjectId = sub.SubjectID
select*from dbo.getScore(); select*from dbo.getScore() where name ='金蝶'
--求出平均工资最高的部门的编号和部门的平均工资 select top 1 deptno, avg(sal) "avg_sal" --不可移植 top在SQL server存在 from emp groupby deptno orderby avg_sal desc --这样子太麻烦 select* from( select deptno, avg(sal) "avg_sal" from emp groupby deptno ) "T" where "T"."avg_sal" = ( selectmax("E"."avg_sal") from ( select deptno, avg(sal) "avg_sal" from emp groupby deptno )"E" ) ---- createview v$_emp_1 as select deptno, avg(sal) "avg_sal" from emp groupby deptno --使用视图后 select*from v$_emp_1 where avg_sal = (selectmax(avg_sal) from v$_emp_1)
总结: 简化查询,避免了代码的冗余
什么是视图
视图从代码上看是一个 select 语句
视图从逻辑上被当作一个虚拟表看待
格式
1 2 3 4 5
createview 视图的名字 as -- 不能添加 begin select 语句 -- 不能添加 end
视图的优缺点
优点
简化查询,增加数据的保密性
课上写的东西
1 2 3 4 5 6 7 8 9
createview view_score as select name, subjectname, score from student stu, subject sub, score s where stu.studentid = s.StudentID and s.SubjectId = sub.SubjectID go
select*from view_score where name ='金蝶'
事物
事物和线程的关系: 事物也是通过锁来解决很多问题的,线程同步也是通过锁来解决的
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
begin transaction declare@errint update bankcard set balance = balance+1000where cardid =10000003 select@err= @@error update bankcard set balance = balance-1000where cardid =10000004 select@err=@err+ @@error if(@err<>0) begin print '转账失败' rollback transaction end else print '成功' commit