SQL SERVER存储过程详解及相关实例

SQL SERVER 存储过程

**相对于视图的优势(为什么使用存储过程):**     Sql Server中视图通过简单的Select查询来解决多次复杂的查询,但是视图不能提供业务逻辑的功能,而存储过程可以。 **什么是存储过程:**
  • 存储过程(Procedure)是一组为了完成特定功能的Sql语句集合,相当于C#中的方法,只编译一次,经编译后存储在数据库中,用户可以通过制定的存储过程名称并给出所需参数来执行
  • 存储过程中可以包含逻辑控制语句和数据操纵语句,它可以接收参数,输出参数,返回单个,多个结果集和返回值。
  • 正是由于存储过程只编译一次,所以它比单个Sql语句块要快速, 所以在一定程度上减少了网络流量,减轻网络负担。

存储过程的优点:

模块化编程 写一次存储过程,可以多次从应用程序的不同部分调用,重复使用
性能 存储过程提供更快的代码执行,减少了网络流量负担。
安全 用户无需使用写任何Sql语句去执行存储过程,防止了Sql注入攻击
可维护性 一组需求改变,修改存储过程即可再次重复调用

存储过程缺点:

不可移植性 每种数据库的内部编程语法都不太相同,当你的系统需要兼容多种数据库时最好不要用存储过程。
学习成本高,DBA一般都擅长写存储过程,但并不是每个程序员都能写好存储过程,除非你的团队有较多的开发人员熟悉写存储过程,否则后期系统维护会产生问题。 存储过程有复杂运算,或者复杂运算过多的话,会增加数据库运行的负担。

SQL SERVER写一个存储过程:

CREATE PROC MyPage
(
@name nvarchar(10),
@page decimal output
)
AS
BEGIN
select * from students
END

执行存储过程:

declare @p decimal--创建Sql变量
declare @n nvarchar(5)
set @n='张三'--为Sql变量赋值
EXEC MyPage @n,@p out--调用存储过程
select @p

修改(删除)存储过程

alter proc proc_name
as
begin
  --sql语句
end  
--删除存储过程
drop proc proc_name

(相关实例)分页存储过程

--存储过程分页
alter PROC NesList
(
@a int,--第几页
@b int,--每页行数
@sum int output,--总行数
@str int output,--总页数
@result nvarchar(100) output--结果
)
AS
BEGIN 

--总行数
Select @sum=count(*) from NewsListTable
--总页数
set @str=CEILING(@sum*1.0/@b)
if(@a<0 or @a>@str)
begin
set @result='页码错误!'
end
--分页数据
select t.NewsId as '新闻编号',t.NewsTitle as '新闻类别',t.NewsDate  as '新闻发布时间' from 
( SELECT  *,RN=ROW_NUMBER() OVER(order by NewsId) FROM NewsListTable) as t where t.RN between ((@a-1)*@b)+1 and @a*@b --between and 包括两边值

END


-------测试存储过程
--测试
declare @nub int
set @nub=-1
declare @nm int
set @nm=2
declare @countsum int
declare @countye int
declare @re nvarchar(100)
exec NesList @nub,@nm,@countsum out,@countye out,@re out
select @countsum,@countye,@re
  • VS调用存储过程实现分页:
 private int a = 1;//第几页
 private int b = 7;//每页数据行数
 private int sum;//总数据行数
 private int str;//总页数
 //利用SqlDataAdapter进行数据读取绑定
            string connstr = "*****************";
            DataTable u = new DataTable();
            using (SqlDataAdapter con = new SqlDataAdapter("USP_Students", connstr))
            {
                con.SelectCommand.CommandType = CommandType.StoredProcedure;
                SqlParameter[] pms = {
                        new SqlParameter ("@A",SqlDbType.Int) {Value=a },
                        new SqlParameter ("@B",SqlDbType.Int) { Value=b},
                        new SqlParameter ("@SUM",SqlDbType.Int) { Direction=ParameterDirection.Output},
                        new SqlParameter ("STR",SqlDbType.Int) { Direction=ParameterDirection.Output}
                    };
                con.SelectCommand.Parameters.AddRange(pms);
                con.Fill(u);
                lblsum.Text = pms[2].Value.ToString();//获取输出参数
                lblye.Text = pms[3].Value.ToString();
                label1.Text = a.ToString();

                this.DGVI.DataSource = u;
            }
发布了21 篇原创文章 · 获赞 3 · 访问量 349

猜你喜欢

转载自blog.csdn.net/MrLsss/article/details/104082972