存储过程

来源:互联网 发布:金庸小说知乎 编辑:程序博客网 时间:2024/05/16 00:57

存储过程是数据库管理系统里的一个很重要的对象。它把多个SQL语句放在一个存储过程里面,起到封装功能的作用。类似在面向对象中,封装对象的一个功能一样。几乎任何可写成批处理的 Transact-SQL 代码都可用于创建存储过程。

存储过程的设计规则包括: 

· CREATE PROCEDURE 定义本身可包括除下列 CREATE 语句以外的任何数量和类型的 SQL 语句,存储过程中的任意地方都不能使用下列语句: 

CREATE DEFAULT

CREATE TRIGGER

CREATE PROCEDURE

CREATE VIEW

CREATE RULE

 

· 可在存储过程中创建其它数据库对象。可以引用在同一存储过程中创建的对象,前提是在创建对象后再引用对象。

· 可以在存储过程内引用临时表。

· 如果在存储过程内创建本地临时表,则该临时表仅为该存储过程而存在;退出该存储过程后,临时表即会消失。

· 如果执行调用其它存储过程的存储过程,那么被调用存储过程可以访问由第一个存储过程创建的、包括临时表在内的所有对象。

· 如果执行在远程 Microsoft® SQL Server™ 2000 实例上进行更改的远程存储过程,则不能回滚这些更改。远程存储过程不参与事务处理。

· 存储过程中参数的最大数目为 2100。

· 存储过程中局部变量的最大数目仅受可用内存的限制。

· 储过程的最大大小可达 128 MB。

创建存储过程

首先要先创建一张表。创建表的SQL代码如下:

--使用我们以前创建的数据库

     use student

go

--在 student数据库里创建表

if exists(select name from sysobjects

           where name='stu'and type='u')

  drop table stu

go

create table stu

(

     s_id int primary key,

    s_name char(20),

    age int not null default 25 ,

    b_id int

)

go

然后给该表插入些数据。代码如下:

--给表插入语句

insert into stu values(1001,'andy',25,101)

insert into stu values(1002,'jacky',16,101)

insert into stu values(1003,'lucy',20,101)

insert into stu values(1004,'gigi',28,102)

insert into stu values(1005,'lray',24,102)

创建不带参数的存储过程:

      --1创建不带参数的存储过程

if exists(select name from sysobjects 

           where name='hh'and type='p')

     drop procedure hh

go

create procedure hh

as

select count(age) 'count'

from stu

where age>20

group by b_id

go

--使用存储过程

exec hh

创建带输入参数的存储过程

--2创建带输入参数的存储过程

if exists(select name from sysobjects

          where name='hc'and type='p')

 drop procedure hc

go

create procedure hc @age int

as

select count(age) 'count'

from stu

where age>@age

group by b_id

go

      --使用存储过程

exec hc 20

 创建带输入,输出参数的存储过程

--3创建带输入,输出参数的存储过程

if exists(select name from sysobjects

          where name='h3'and type='p')

  drop procedure h3

go

create procedure h3 @p1 int,@p2 char(30) output

as

    select @p2=s_name

    from stu

    where s_id=@p1

go

   --调用该存储过程

declare  @out char(30) 

exec h3 1002,@out output

select @out

go


原创粉丝点击