这些例子都是我平时积累总结的

 
  
  1. set statistics io on 
  2. --查询选修了003号课程并且分数在80分以上的所有学生信息  
  3. --第一句开销小,第二句开销大  
  4. select * from student where sno=(select sno from sc where cno=003 and grade>80)  
  5. select * from student where 80<=(select grade from sc where student.sno=sc.sno and cno=003)  
  6.  
  7. --查询至少选修了2门课程的学生所有信息,从系统开销来看还是第一个的效率高  
  8. select * from student where 2<=(select count(cno) from sc where student.sno=sc.sno)  
  9. select * from student where sno in (select sno from sc group by sno having count(cno)>=2)  
  10.  
  11. --在学生表student和学生选课表sc中找出所有学生选修的课程其平均成绩大于75分的学生所有信息  
  12. select * from student where 75<(select avg(grade) from sc where student.sno=sc.sno)  
  13. select * from student where sno in(select sno from sc group by sno having avg(grade)>75)  
  14.  
  15. --在学生表student和学生选课表sc中找出所有学生选修了课程001的学生学号,姓名,性别,年龄,和所属系部信息  
  16. select sno,sname,sgentle,sage,sdept from student where sno in(select sno from sc where cno=001)  
  17. select sno,sname,sgentle,sage,sdept from student where 001 in(select cno from sc where student.sno=sc.sno)  
  18.  
  19. --查询学生表student中平均年龄小于该系其中某一个学生的年龄  
  20. select sdept,avg(sage) from student a group by a.sdept having avg(sage)< any(select sage from student b where a.sdept=b.sdept)  
  21.  
  22. --选取计算机系学生选修了"数据结构"课程的学生基本信息,并按年龄降序排列  
  23. --同样的,第一个效率高  
  24. select * from student where sno in (  
  25. select sno from sc where cno in(  
  26. select cno from course where cname='数据结构'))and sdept='计算机' order by sage desc 
  27.  
  28. select student.* from student join sc  
  29. on student.sno=sc.sno join course  
  30. on course.cno=sc.cno   
  31. where student.sdept='计算机' and 
  32. course.cname='数据结构' 
  33. order by sage desc 
  34.  
  35. --查询姓名'张忠和'的学生所选修课程'软件工程'的成绩  
  36. select grade from sc where cno in(select cno from course where cname='软件工程'and sno=(select sno from student where sname='张忠和')  
  37.  
  38. create table studenttest(  
  39. sno varchar(10) primary key,  
  40. sname varchar(10) not null,  
  41. sgentle varchar(2) not null,  
  42. sage int,  
  43. sbirth smalldatetime,  
  44. sdept varchar(20) not null 
  45. )  
  46. sp_help student  
  47.  
  48. --大数据的复制  
  49. bulk insert stored.dbo.studenttest from 'c:\test.txt' 
  50. --xp_cmdshell是要调用系统中的cmd,在执行这个时要先配置path环境变量  
  51. EXEC xp_cmdshell 'bcp stored.dbo.student out c:\test1.txt -c -T' 
  52. --将数据导入到数据库中,导入的时候要注意时间日期的问题,导入的格式要与数据库中的设定格式要一致  
  53. exec xp_cmdshell 'bcp stored.dbo.studenttest in c:\test1.txt -c -T'