存储过程

来源:互联网 发布:80端口哪个运营商 编辑:程序博客网 时间:2024/06/03 23:50

因为此次编程用到了存储过程,之前在学习数据库视频的时候就一带而过了,现在又回头重温一遍。

什么是存储过程:

存储过程可以说是一个记录集,它是由一些T—SQL语句组成的代码块,这些T—SQL语句组成的代码就像一个方法一样实现一些功能(对单表或多表的增删改查),然后再给这个代码块取一个名字,在用户到这个功能的时候调用它就可以了。

它的优点:

由于存储过程在创建时即在数据库服务器上进行了编译并存储在数据库中,所以存储过程运行要比单个的SQL语句块要快,同事由于在调用时只需要提供存储过程名和必要的参数信息,所以在一定程度上也可以减少网络流量、简单网络负担。

我们在现实中需要的是用户自定义的存储过程,下面来看它的语法:

1、创建语法:

create proc | procedure pro_name    [{@参数数据类型} [=默认值] [output],     {@参数数据类型} [=默认值] [output],     ....    ]as    SQL_statements

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

--创建存储过程if (exists (select * from sys.objects where name = 'proc_get_student'))    drop proc proc_get_studentgocreate proc proc_get_studentas    select * from student;--调用、执行存储过程exec proc_get_student;

3、修改存储过程:

alter proc proc_get_studentasselect * from student;

4、带参存储过程:

--带参存储过程if (object_id('proc_find_stu', 'P') is not null)    drop proc proc_find_stugocreate proc proc_find_stu(@startId int, @endId int)as    select * from student where id between @startId and @endIdgoexec proc_find_stu 2, 4;

5、带通配符存储过程:
--带通配符参数存储过程if (object_id('proc_findStudentByName', 'P') is not null)    drop proc proc_findStudentByNamegocreate proc proc_findStudentByName(@name varchar(20) = '%j%', @nextName varchar(20) = '%')as    select * from student where name like @name and name like @nextName;goexec proc_findStudentByName;exec proc_findStudentByName '%o%', 't%';

6、带输出参数存储过程:
if (object_id('proc_getStudentRecord', 'P') is not null)    drop proc proc_getStudentRecordgocreate proc proc_getStudentRecord(    @id int, --默认输入参数    @name varchar(20) out, --输出参数    @age varchar(20) output--输入输出参数)as    select @name = name, @age = age  from student where id = @id and sex = @age;go-- declare @id int,        @name varchar(20),        @temp varchar(20);set @id = 7; set @temp = 1;exec proc_getStudentRecord @id, @name out, @temp output;select @name, @temp;print @name + '#' + @temp;

以上是几种常用的存储过程的方法,存储过程在大的应用系统为减少代码量起了很大的作用,同事也是一种重要的数据库技术。
0 0
原创粉丝点击