zoukankan      html  css  js  c++  java
  • SQL Server存储过程的使用

     

     存储过程概述

      简单来说,存储过程就是一条或者多条sql语句的集合,可视为批处理文件,但是其作用不仅限于批处理。

     基本概念:

      SQL Server中的存储过程是使用T_SQL编写的代码段。它的目的在于能够方便的从系统表中查询信息,

      或者完成与更新数据库表相关的管理任务和其他的系统管理任务.T_SQL语句是SQL Server数据库与应用程序之间的编程接口。

      存储过程就是SQL Server为了实现特定任务,而将一些需要多次调用的固定操作语句编写成程序段,这些程序段存储在服务器上,

      有数据库服务器通过程序来调用。

    • 为什么要使用存储过程?不使用存储过程会怎么样?

        在很多情况下,一些代码会被开发者重复编写多次,如果每次都编写相同功能的代码,不但繁琐,而且容易出错,

        如果不使用的话,SQL Server逐条的执行语句会降低系统的运行效率。

    • 存储过程的优点:
    1. 存储过程加快系统运行速度,存储过程只在创建时编译,以后每次执行时不需要重新编译。
    2. 存储过程可以封装复杂的数据库操作,简化操作流程,例如对多个表的更新,删除等。
    3. 可实现模块化的程序设计,存储过程可以多次调用,提供统一的数据库访问接口,改进应用程序的可维护性。
    4. 存储过程可以增加代码的安全性,对于用户不能直接操作存储过程中引用的对象,SQL  Server可以设定用户对指定存储过程的执行权限。
    • 存储过程的缺点:
    1. 数据库移植不方便,存储过程依赖与数据库管理系统, SQL Server 存储过程中封装的操作代码不能直接移植到其他的数据库管理系统中。
    2. 不支持面向对象的设计,
    3. 代码可读性差,不易维护。不支持集群。

      存储过程分类

    • 系统存储过程

      系统存储过程是 SQL Server系统自身提供的存储过程,可以作为命令执行各种操作。

        系统存储过程主要用来从系统表中获取信息,使用系统存储过程完成数据库服务器的管理工作,为系统管理员提供帮助,

        为用户查看数据库对象提供方便,系统存储过程位于数据库服务器中,并且以sp_开头

        系统存储过程创建并存放在与系统数据库master中,一些系统存储过程只能由系统管理员使用,而有些系统存储过程通过授权可以被其它用户所使用。

    • 用户存储过程(自定义存储过程)

        自定义存储过程即用户使用T_SQL语句编写的、为了实现某一特定业务需求,在用户数据库中编写的T_SQL语句集合,

        自定义存储过程可以接受输入参数、向客户端返回结果和信息,返回输出参数等。创建自定义存储过程时,

        存储过程名前加上"##"表示创建了一个全局的临时存储过程;存储过程前面加上"#"时,表示创建的局部临时存储过程。

        局部临时存储过程只能在创建它的回话中使用,会话结束时,将被删除。这两种存储过程都存储在tempdb数据库中。

        T_SQL:存储过程是值保存的T_SQL语句集合,可以接受和返回用户提供的参数,存储过程也可能从数据库向客户端应用程序返回数据。

       创建存储过程

     1 use bookdb;
     2 --创建测试books表
     3 create table books (
     4     book_id int identity(1,1) primary key,
     5     book_name varchar(20),
     6     book_price float,
     7     book_author varchar(10)
     8 );
     9 --插入测试数据
    10 insert into books (book_name,book_price,book_author) values
    11 ('论语',25.6,'孔子'),                                   
    12  ('平凡的世界',35.8,'路遥');
    13                        
    • 创建无参存储过程

    1 --1.创建无参存储过程
    2 if (exists (select * from sys.objects where name = 'getAllBooks'))
    3     drop proc proc_get_student
    4 go
    5 create procedure getAllBooks
    6 as
    7 select * from books;
    8 --调用,执行存储过程
    9 exec getAllBooks;
      • 修改存储过程

    1 alter procedure dbo.getAllBooks 
    2 as
    3 select book_author  from books;       
      • 删除存储过程

         drop procedure getAllBooks; 

      • 重命名存储过程

         sp_rename getAllBooks,proc_get_allBooks; 

     

    • 创建带参数的存储过程

      存储过程的参数分为两种:输入参数和输出参数

      输入参数:用于向存储过程传入值,类似java语言或则c中的值传递。

      输出参数:用于调用存储过程后,参会结果,类似java语言的按引用传递。

      值传递和引用传递区别:

    • 基本数据类型赋值属于值传递;引用类型之间赋值属于引用传递。
    • 值传递传递的是实实在在的变量值;引用传递传递的是对象的引用地址。
    • 值传递后,两个变量改变的是各自的值;引用传递后,两个引用改变的是同一个对象的状态

      (a)带一个参数存储过程

    1 if (exists (select * from sys.objects where name = 'searchBooks'))
    2     drop proc searchBooks
    3 go
    4 create proc searchBooks(@bookID int)
    5 as
    6     --要求book_id列与输入参数相等
    7     select * from books where book_id=@bookID;
    8 --执行searchBooks
    9 exec searchBooks 1;

      

      (b)带2个参数存储过程

     1 if (exists (select * from sys.objects where name = 'searchBooks1'))
     2     drop proc searchBooks1
     3 go
     4 create proc searchBooks1(
     5     @bookID int,
     6     @bookAuth varchar(20)
     7 )
     8 as
     9     --要求book_id和book_Auth列与输入参数相等
    10     select * from books where book_id=@bookID and book_auth=@bookAuth;
    11 exec searchBooks1 1,'金庸';

      (c)创建有返回值的存储过程

     1 if (exists (select * from sys.objects where name = 'getBookId'))
     2     drop proc getBookId
     3 go
     4 create proc getBookId(
     5     @bookAuth varchar(20),--输入参数,无默认值
     6     @bookId int output --输入/输出参数 无默认值
     7 )
     8 as
     9     select @bookId=book_id from books where book_auth=@bookAuth
    10 --执行getBookId这个带返回值的存储过程
    11 declare @id int --声明一个变量用来接收执行存储过程后的返回值
    12 exec getBookId '孔子',@id output
    13 select @id as bookId;--as是给返回的列值起一个名字

      (d)创建带通配符的存储过程

     1 if (exists (select * from sys.objects where name = 'charBooks'))
     2     drop proc charBooks
     3 go
     4 create proc charBooks(
     5     @bookAuthor varchar(20)='金%',
     6     @bookName varchar(20)='%'
     7 )
     8 as 
     9     select * from books where book_author like @bookAuth and book_name like @bookName;
    10 --执行存储过程charBooks
    11 exec  charBooks    '孔%','论%';

        

      (e)创建分页存储过程

     1 if (object_id('book_page', 'P') is not null)
     2     drop proc book_page
     3 go
     4 create proc book_page(
     5     @TableName varchar(50),            --表名
     6     @ReFieldsStr varchar(200) = '*',   --字段名(全部字段为*)
     7     @OrderString varchar(200),         --排序字段(必须!支持多字段不用加order by)
     8     @WhereString varchar(500) =N'',  --条件语句(不用加where)
     9     @PageSize int,                     --每页多少条记录
    10     @PageIndex int = 1 ,               --指定当前为第几页
    11     @TotalRecord int output            --返回总记录数
    12 )
    13 as
    14 begin
    15      --处理开始点和结束点
    16     Declare @StartRecord int;
    17     Declare @EndRecord int; 
    18     Declare @TotalCountSql nvarchar(500); 
    19     Declare @SqlString nvarchar(2000);    
    20     set @StartRecord = (@PageIndex-1)*@PageSize + 1
    21     set @EndRecord = @StartRecord + @PageSize - 1 
    22     SET @TotalCountSql= N'select @TotalRecord = count(*) from ' + @TableName;--总记录数语句
    23     SET @SqlString = N'(select row_number() over (order by '+ @OrderString +') as rowId,'+@ReFieldsStr+' from '+ @TableName;--查询语句
    24     --
    25     IF (@WhereString! = '' or @WhereString!=null)
    26         BEGIN
    27             SET @TotalCountSql=@TotalCountSql + '  where '+ @WhereString;
    28             SET @SqlString =@SqlString+ '  where '+ @WhereString;            
    29         END
    30     --第一次执行得到
    31     --IF(@TotalRecord is null)
    32     --   BEGIN
    33            EXEC sp_executesql @totalCountSql,N'@TotalRecord int out',@TotalRecord output;--返回总记录数
    34     --  END
    35     ----执行主语句
    36     set @SqlString ='select * from ' + @SqlString + ') as t where rowId between ' + ltrim(str(@StartRecord)) + ' and ' +  ltrim(str(@EndRecord));
    37     Exec(@SqlString)    
    38 END
    39 --调用分页存储过程book_page
    40 exec book_page 'books','*','book_id','',3,1,0;
    41 
    42 --
    43 declare @totalCount int
    44 exec book_page 'books','*','book_id','',3,1,@totalCount output; 
    45 select @totalCount as totalCount;--总记录数。
  • 相关阅读:
    三个Bootstrap免费字体和图标库
    前端实时消息提示的效果-websocket长轮询
    带分页的标签
    VMware-workstation安装
    摄影/肥猫的大头贴
    Smith Numbers(分解质因数)
    C
    B
    Ball
    Property Distribution(DFS)
  • 原文地址:https://www.cnblogs.com/lhy-549/p/10088553.html
Copyright © 2011-2022 走看看