Transact-SQL中的存储过程,非常类似于Java语言中的方法,它可以重复调用。当存储过程执行一次后,可以将语句缓存中,这样下次执行的时候直接使用缓存中的语句。这样就可以提高存储过程的性能。

存储过程的概念

存储过程Procedure是一组为了完成特定功能的SQL语句集合,经编译后存储在数据库中,用户通过指定存储过程的名称并给出参数来执行。

存储过程中可以包含逻辑控制语句和数据操纵语句,它可以接受参数、输出参数、返回单个或多个结果集以及返回值。

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

1、 存储过程的优点

A、 存储过程允许标准组件式编程

存储过程创建后可以在程序中被多次调用执行,而不必重新编写该存储过程的SQL语句。而且数据库专业人员可以随时对存储过程进行修改,但对应用程序源代码却毫无影响,从而极大的提高了程序的可移植性。

B、 存储过程能够实现较快的执行速度

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

C、 存储过程减轻网络流量

对于同一个针对数据库对象的操作,如果这一操作所涉及到的T-SQL语句被组织成一存储过程,那么当在客户机上调用该存储过程时,网络中传递的只是该调用语句,否则将会是多条SQL语句。从而减轻了网络流量,降低了网络负载。

D、 存储过程可被作为一种安全机制来充分利用

系统管理员可以对执行的某一个存储过程进行权限限制,从而能够实现对某些数据访问的限制,避免非授权用户对数据的访问,保证数据的安全。

系统存储过程

系统存储过程是系统创建的存储过程,目的在于能够方便的从系统表中查询信息或完成与更新数据库表相关的管理任务或其他的系统管理任务。系统存储过程主要存储在master数据库中,以“sp”下划线开头的存储过程。尽管这些系统存储过程在master数据库中,但我们在其他数据库还是可以调用系统存储过程。有一些系统存储过程会在创建新的数据库的时候被自动创建在当前数据库中。

常用系统存储过程有:

exec sp_databases; --查看数据库
exec sp_tables; --查看表
exec sp_columns student;--查看列
exec sp_helpIndex student;--查看索引
exec sp_helpConstraint student;--约束
exec sp_stored_procedures;
exec sp_helptext 'sp_stored_procedures';--查看存储过程创建、定义语句
exec sp_rename student, stuInfo;--修改表、索引、列的名称
exec sp_renamedb myTempDB, myDB;--更改数据库名称
exec sp_defaultdb 'master', 'myDB';--更改登录名的默认数据库
exec sp_helpdb;--数据库帮助,查询数据库信息
exec sp_helpdb master;
    系统存储过程示例:
--表重命名
exec sp_rename 'stu', 'stud';
select * from stud;
--列重命名
exec sp_rename 'stud.name', 'sName', 'column';
exec sp_help 'stud';
--重命名索引
exec sp_rename N'student.idx_cid', N'idx_cidd', N'index';
exec sp_help 'student'; --查询所有存储过程
select * from sys.objects where type = 'P';
select * from sys.objects where type_desc like '%pro%' and name like 'sp%';

用户自定义存储过程

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_student
go
create proc proc_get_student
as
select * from student; --调用、执行存储过程
exec proc_get_student;

3、 修改存储过程

--修改存储过程
alter proc proc_get_student
as
select * from student;

4、 带参存储过程

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

5、 带通配符参数存储过程

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

6、 带输出参数存储过程

if (object_id('proc_getStudentRecord', 'P') is not null)
drop proc proc_getStudentRecord
go
create 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;
 

7、 不缓存存储过程

--WITH RECOMPILE 不缓存
if (object_id('proc_temp', 'P') is not null)
drop proc proc_temp
go
create proc proc_temp
with recompile
as
select * from student;
go exec proc_temp;

8、 加密存储过程

--加密WITH ENCRYPTION 
if (object_id('proc_temp_encryption', 'P') is not null)
drop proc proc_temp_encryption
go
create proc proc_temp_encryption
with encryption
as
select * from student;
go exec proc_temp_encryption;
exec sp_helptext 'proc_temp';
exec sp_helptext 'proc_temp_encryption';

9、 带游标参数存储过程

if (object_id('proc_cursor', 'P') is not null)
drop proc proc_cursor
go
create proc proc_cursor
@cur cursor varying output
as
set @cur = cursor forward_only static for
select id, name, age from student;
open @cur;
go
--调用
declare @exec_cur cursor;
declare @id int,
@name varchar(20),
@age int;
exec proc_cursor @cur = @exec_cur output;--调用存储过程
fetch next from @exec_cur into @id, @name, @age;
while (@@fetch_status = 0)
begin
fetch next from @exec_cur into @id, @name, @age;
print 'id: ' + convert(varchar, @id) + ', name: ' + @name + ', age: ' + convert(char, @age);
end
close @exec_cur;
deallocate @exec_cur;--删除游标
 

10、 分页存储过程

---存储过程、row_number完成分页
if (object_id('pro_page', 'P') is not null)
drop proc proc_cursor
go
create proc pro_page
@startIndex int,
@endIndex int
as
select count(*) from product
;
select * from (
select row_number() over(order by pid) as rowId, * from product
) temp
where temp.rowId between @startIndex and @endIndex
go
--drop proc pro_page
exec pro_page 1, 4
--
--分页存储过程
if (object_id('pro_page', 'P') is not null)
drop proc pro_stu
go
create procedure pro_stu(
@pageIndex int,
@pageSize int
)
as
declare @startRow int, @endRow int
set @startRow = (@pageIndex - 1) * @pageSize +1
set @endRow = @startRow + @pageSize -1
select * from (
select *, row_number() over (order by id asc) as number from student
) t
where t.number between @startRow and @endRow; exec pro_stu 2, 2;
 

Raiserror

Raiserror返回用户定义的错误信息,可以指定严重级别,设置系统变量记录所发生的错误。

语法如下:

Raiserror({msg_id | msg_str | @local_variable}
{, severity, state}
[,argument[,…n]]
[with option[,…n]]
)

# msg_id:在sysmessages系统表中指定的用户定义错误信息

# msg_str:用户定义的信息,信息最大长度在2047个字符。

# severity:用户定义与该消息关联的严重级别。当使用msg_id引发使用sp_addmessage创建的用户定义消息时,raiserror上指定严重性将覆盖sp_addmessage中定义的严重性。

任何用户可以指定0-18直接的严重级别。只有sysadmin固定服务器角色常用或具有alter trace权限的用户才能指定19-25直接的严重级别。19-25之间的安全级别需要使用with log选项。

# state:介于1至127直接的任何整数。State默认值是1。

raiserror('is error', 16, 1);
select * from sys.messages;
--使用sysmessages中定义的消息
raiserror(33003, 16, 1);
raiserror(33006, 16, 1);

存储过程系列之存储过程具体操作过程及sql数据库调用的更多相关文章

  1. 存储过程系列之存储过程sql数据库调用和程序代码调用

    1.存储过程,无参数的存储过程 创建无参数存储存储过程 Create Procedure DCEMREMR_TEMPLATEAs SELECT TOP 10 [FILENAME],[FILETITLE ...

  2. 存储过程系列之存储过程sql查询存储过程的使用

    1.查询某个表被哪些存储过程(以下简称 SP)使用到 : select distinct object_name(id) from syscomments where id in (select ob ...

  3. Sql Server系列:存储过程

    1 存储过程简介 存储过程是使用T-SQL代码编写的代码段.在存储过程中,可以声明变量.执行条件判断语句等其他编程功能.在MS SQL Server 2012中存储过程主要分三类:系统存储过程.自定义 ...

  4. 存储过程系列之调试存储过程 SQL Server 2005

    在数据库中直接调试  在数据库中直接调试是调试SQL Server 2005的存储过程的最简单的方法. 在Visual Stuido的IDE中你可以选择单步执行存储过程,然后就可以一条语句一条语句地单 ...

  5. SQL Server 2008 存储过程,带事务的存储过程(创建存储过程,删除存储过程,修改存储过

    SQL Server 2008 存储过程,带事务的存储过程(创建存储过程,删除存储过程,修改存储过     存储过程 创建存储过程 use pubs --pubs为数据库 go create proc ...

  6. SQL 语句调用这个存储过程,生成顺序编码

    一直很讨厌存储过程,没想到今天帮了我大忙啊,或许会因为今天让我慢慢喜欢上存储过程吧,不多说了,切入正题 在使用数据库的时候,难免要在使用过程中进行删除的操作,如果是使用int类型的字段,令其自增长,这 ...

  7. ADO.NET访问SQL Server调用存储过程带回参

    1,ADO.NET访问SQL Server调用存储过程带回参 2,DatabaseDesign  use northwind go --存储过程1 --插入一条商品 productname=芹菜 un ...

  8. 存储过程学习笔记(SQL数据库

    一.   存储过程简介 Sql Server的存储过程是一个被命名的存储在服务器上的Transacation-Sql语句集合,是封装重复性工作的一种方法,它支持用户声明的变量.条件执行和其他强大的编程 ...

  9. 在PL/SQL中调用Oracle存储过程

    存储过程 1 什么是存储过程? 用于在数据库中完成特定的操作或者任务.是一个PLSQL程序块,可以永久的保存在数据库中以供其他程序调用. 2 存储过程的参数模式 存储过程的参数特性: IN类型的参数 ...

随机推荐

  1. ### MATLAB - CUDA

    MATLAB下使用CUDA. #@author: gr #@date: 2014-04-08 #@email: forgerui@gmail.com 一. Matlab & C 1. 概念 M ...

  2. 关于Encoding.GetEncoding("utf-8")和Encoding.GetEncoding("GB2312")及Encoding.Default

    关于Encoding.GetEncoding("utf-8")和Encoding.GetEncoding("GB2312")及Encoding.Default ...

  3. 【html】【11】函数名称约束规范

    一.匈牙利命名法: [不推荐]基本原则是:变量名=属性+类型+对象描述,其中每一对象的名称都要求有明确含义,可以取对象名字全称或名字的一部分.要基于容易记忆容易理解的原则.保证名字的连贯性是非常重要的 ...

  4. redis 实践—— sorted set, hash set

    在这里就不谈redis的安装与启动啦,网上太多人写这个了. 从最近的一个项目[钻石夺宝]说起,如果大家有玩过一元夺宝或者全名夺宝的话,大概会知道如果参与人数多的话,每隔几秒.快的话每隔一秒都会新生成一 ...

  5. css3中的BFC,IFC,GFC和FFC(转载)

    作者原文网址:http://www.cnblogs.com/dingyufenglian/p/4845477.html   What‘s FC? 一定不是KFC,FC的全称是:Formatting C ...

  6. linux 定时执行 cron指令

    linux 中的 cron 定时执行命令,先上例子:每间隙两分钟把 "Hello world"写到 /tmp/hello.txt crontab -e */2 * * * * ec ...

  7. php 加密解密方法2

    <?php /* * @param $string 要加密或解决的字符串 * @param $operation 加密/解密 ENCODE加密, DECODE 解密 * @param $key ...

  8. c#的多线程

    多线程的使用方法: Thread t = new Thread(new ThreadStart (StartMethod)); t.Start(); private void StartMethod( ...

  9. 使用.htaccess进行浏览器图片文件缓存

    对于图片类网站,每次打开页面都要重新下载图片,慢不说,还非常浪费流量.这时就需要用到缓存,强制浏览器缓存图片文件 缓存文件,提问网站访问数度,减少流量消耗,现提供2中缓存代码 打开.htaccess文 ...

  10. PHP LINUX Notice: undefined $_GET完美解决方法

    PHP Notice: undefined 平时用$_GET[‘xx’] 取得参数值时,如果之前不加判断在未传进参数时会出现这样的警告: PHP Notice: undefined index xxx ...