1. --存储过程  
  2. ---要创建存储过程的数据库  
  3. USE MyTest   
  4. if exists (select name from sysobjects where name ='sp_addInfo' and type='P')  
  5. --删除存储过程  
  6. Drop procedure dbo.sp_addInfo  
  7. GO  
  8. --创建存储过程  
  9. create proc dbo.sp_addInfo  
  10. --存储过程参数  
  11. @name varchar(20),  
  12. @sex bit,  
  13. @class varchar(20)  
  14.  
  15. as   
  16. begin  
  17. --存储过程语句体  
  18. insert into student(name,sex,class)  
  19. values(@name,@sex,@class)  
  20.  
  21. end  
  22.  
  23. exec sp_addInfo 'QQQQ',0,'2222'  
  24.  
  25. truncate table student   
  26. --truncate 删除表中的所有行数据,而不记录每个行删除操作,不能带条件  
  27. /*truncate table 在功能上与不带where字句的Delete语句相同,均删除表中的所有记录  
  28.  
  29. 但 TRUNCATE TABLE 比 Delete 速度快,且使用的系统和事务日志资源少。  
  30. Delete 语句每次删除一行,并在事务日志中为所删除的每行记录一项。TRUNCATE TABLE 通过  
  31. 释放存储表数据所用的数据页来删除数据,并且只在事务日志中记录页的释放  
  32.  
  33. TRUNCATE TABLE 删除表中的所有行,但表结构及其列、约束、索引等保持不变。新行标识所用  
  34. 的计数值重置为该列的种子。如果想保留标识计数值,请改用 Delete。如果要删除表定义及其数据,请  
  35. 使用 Drop TABLE 语句  
  36.  
  37. 对于由 FOREIGN KEY 约束引用的表,不能使用 TRUNCATE TABLE,而应使用不带 Where 子句的  
  38. Delete 语句  
  39. TRUNCATE TABLE 不记录在日志中,所以它不能激活触发器  
  40. TRUNCATE TABLE 不能用于参与了索引视图的表。  
  41.  
  42. */  
  43. GO  
  44. --循环插入记录的例子 --游标使用  
  45. declare @Id int  
  46. begin  
  47. declare db cursor for   
  48. select id from student3   
  49. end   
  50. open db   
  51. fetch next from db into @Id  
  52. while @@FETCH_STATUS=0   
  53. begin   
  54. insert into student(name,sex,class)   
  55. select name,sex,class  from student3 where id=@Id   
  56. fetch next from db into @Id  
  57. end  
  58. close db  
  59. deallocate db  
  60.  
  61. --或  
  62.  
  63. declare @name varchar(20)  
  64. declare @sex bit  
  65. declare @class varchar(20)  
  66. begin  
  67. declare db cursor local scroll for select name,sex,class from  student3  
  68. end   
  69. open db   
  70. fetch next from db into @name,@sex,@class  
  71. while @@FETCH_STATUS=0   
  72. begin   
  73. insert into student(name,sex,class)   
  74. values(@name,@sex,@class)  
  75. fetch next from db into @name,@sex,@class  
  76. end  
  77. close db  
  78. deallocate db  
  79.  

 

存储过程 优点: 

1.存储过程允许标准组件式编程(模块化设计)
存储过程在被创建以后,可以在程序中被多次调用,而不必重新编写该存储过程的SQL语句,而且数据库专业人员可随时对存储过程进行修改,但对应用程序源代码毫无影响。因为应用程序源代码只包含存过程的调用语句,从而极大地提高了程序的可移植性。

2.存储过程能够实现快速的执行速度
   如果某一操作包含大量的Transaction-SQL 代码,,或分别被多次执行,那么存储过程要比批处理的执行速度快很多,因为存储过程是预编译的,在首次运行一个存储过程时,查询优化器对其进行分析优化,并给出最终被存在系统表中的执行计划,而批处理的Transaction-SQL 语句在每次运行时都要进行编译和优化,因此速度相对要慢一些。

3.存储过程能够减少网络流量
   对于同一个针对数据数据库对象的操作,如查询修改,如果这一操作所涉及到的Transaction-SQL 语句被组织成一存储过程,那么当在客户计算机上调用该存储过程时,网络中传送的只是该调用语句,否则将是多条SQL 语句从而大大增加了网络流量降低网络负载。

4.存储过程可被作为一种安全机制来充分利用
   系统管理员通过,对执行某一存储过程的权限进行限制,从而能够实现对相应的数据访问权限的限制。