大家好,又见面了,我是你们的朋友全栈君。
**相对于视图的优势(为什么使用存储过程):** Sql Server中视图通过简单的Select查询来解决多次复杂的查询,但是视图不能提供业务逻辑的功能,而存储过程可以。 **什么是存储过程:**
存储过程的优点:
模块化编程 | 写一次存储过程,可以多次从应用程序的不同部分调用,重复使用 |
---|---|
性能 | 存储过程提供更快的代码执行,减少了网络流量负担。 |
安全 | 用户无需使用写任何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
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;
}
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。
发布者:全栈程序员栈长,转载请注明出处:https://javaforall.cn/185587.html原文链接:https://javaforall.cn
扫码关注腾讯云开发者
领取腾讯云代金券
Copyright © 2013 - 2025 Tencent Cloud. All Rights Reserved. 腾讯云 版权所有
深圳市腾讯计算机系统有限公司 ICP备案/许可证号:粤B2-20090059 深公网安备号 44030502008569
腾讯云计算(北京)有限责任公司 京ICP证150476号 | 京ICP备11018762号 | 京公网安备号11010802020287
Copyright © 2013 - 2025 Tencent Cloud.
All Rights Reserved. 腾讯云 版权所有