潇湘一夜雨

SQL Server 存储过程

Ø 存储过程的概念

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

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

常用系统存储过程有:

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,--输入输出参数
    @sex int --默认输入参数
)
as
    --用select 给变量@name,@age 赋值。赋的值为从student表中查出的name,和age字段
    select @name = name, @age = age  from student where id = @id and sex = @sex;

    --也可以写成:set @name=(select name from student where id=@id and sex=@sex)
    --          set @age=(select age from student where id=@id and sex=@sex)
go

---------------------------------------------------------------------------------------带参数的存储过程调用如下: 
declare @id int,                         -----先声明参数。也可以不声明。在调用存储过程的时候直接写值也是可以的
        @name varchar(20),
        @temp varchar(20),
        @sex int
set @id = 7;                 --再给参数赋值
set @sex=0;
set @temp = 1;
exec proc_getStudentRecord @id, @name out, @temp output,@sex;           --调用存储过程

select @name, @temp;--打印出@name,@temp

 

(2) 

create proc p_xs_sum
(
    @xh int,
    @kcm nvarchar(20),
    @sum int output
)
as
select @sum=总学分 from xs join xs_kc join kc  on xs_kc.课程号=kc.课程号 on xs.学号=xs_kc.学号 
where xs.学号=@xh  and 课程名=@kcm

go
------------------------存储过程的调用
declare @xh int,
        @kcm nvarchar(20),
        @sum int
        
set @xh='001101';
set @kcm='离散数学';
        

exec p_xs_sum @xh,@kcm, @sum out
print @sum 

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);

 

Ø 使用While遍历表

create proc Proc_TestWhile(@age int)
as
declare @temp table --声明一个名字为@temp的临时表变量(用于存储查询出来的数据)
(
    Id int ,
    Name nvarchar(50),
    Age int ,
    Gender int ,
    Mobile varchar(50) ,
    Email varchar(50) ,
    Addres nvarchar(100) ,
    Reamarks nvarchar(500) ,
    LoginId int ,
    UserName nvarchar(50)
 );
 insert into @temp (Id,Name,Age,Gender,Mobile,Email,Addres,Reamarks,LoginId,UserName)
 select a.*,b.UserName from t_userinfo a join  T_UserLogin b on a.LoginId=b.LoginId where a.age>@age
 order by a.Id --将查询出来的数据插入到@temp这个临时表变量中
  
declare --声明变量(为后面的插入语句使用)
    @Id int ,
    @Name nvarchar(50),
    @Age2 int ,
    @Gender int ,
    @Mobile varchar(50) ,
    @Email varchar(50) ,
    @Addres nvarchar(100) ,
    @Reamarks nvarchar(500) ,
    @LoginId int ,
    @UserName nvarchar(50)
while exists(select id from @temp)--使用while语句进行循环,如果@temp临时表中还有数据就一直循环
begin
    set rowcount 1 --使用set rowcount是为了使后续的查询、更新、删除操作只影响指定的行数
    select                                @Id=id,@Name=name,@Age2=age,@Gender=gender,@Mobile=Mobile,@Email=Email,@Addres=Addres,@Reamarks=Reamarks,@LoginId=LoginId,@UserName=UserName from @temp; --将变量赋值

    insert into T_UserInfoTwo values(@Id,@Name,@Age2,@Gender,@Mobile,@Email,@Addres,@Reamarks,@LoginId,@UserName)
    set rowcount 0

     delete from @temp where id=@Id;--插入一条后,就将临时表中的这条数据删除
end


--exec TestWhile 24

 

 

本文出自: http://www.cnblogs.com/hoojo/archive/2011/07/19/2110862.html 

posted on 2014-07-03 14:51  潇湘一夜雨  阅读(765)  评论(0)    收藏  举报

导航