您的位置:首页 > 编程语言 > C#

存储过程和C#中调用详解

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

Ø 存储过程的概念

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

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

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

1、 存储过程的优点

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

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

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

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

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

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

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

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

C#调用存储过程

存储过程
exec sp_databases           --执行过程
declare @Studnet int
set @Studnet=243
exec sp_helptext @Studnet
exec sp_helptext 存储过程名

--创建
create proc usp_GetStudentById
@Id int
as
select * from Student where id=@Id

alter proc usp_GetStudentByIdAndName
@Id int,
@Name varchar(10)   --长度
as
select * from Student where id=@Id and name=@Name

alter proc usp_GetStudent       --修改 alter
as
begin
select * from Student where id='1'
select * from Student
end

--分页
alter proc usp_GetPageStudnetRowNum

@pageindex int=1
as
begin
select * from
(
select *,ROW_NUMBER() over(order by ID) AS rownum
from Student) as a
where a.rownum >(@pageindex-1)*5 and a.rownum<= @pageindex*5
end

exec usp_GetPageStudnetRowNum 2

--调用
exec sp_helptext usp_GetStudentById

exec usp_GetStudentById '1'   --参数

exec usp_GetStudentByIdAndName @Id='5',@Name='few'    --多个参数

exec usp_GetStudent

--分页
create proc usp_GetPageStudnetRowNum2

@pageindex int=1,
@countnum int=5
as
begin
select * from
(
select *,ROW_NUMBER() over(order by ID) AS rownum
from Student) as a
where a.rownum >(@pageindex-1)*@countnum and a.rownum<= @pageindex*@countnum
end

exec usp_GetPageStudnetRowNum2    --全默认
exec usp_GetPageStudnetRowNum2 @countnum=3
exec usp_GetPageStudnetRowNum2 @pageindex=3,@countnum=3

--输入参数
declare @p int,@c int
set @p=2
set @c=3
exec usp_GetPageStudnetRowNum2 @p,@c

alter proc usp_GetPageStudnetRowNum3

@pageindex int=1,
@countnum int=5,
@rowcount int output
as
begin
select * from
(
select *,ROW_NUMBER() over(order by ID) AS rownum
from Student) as a
where a.rownum >(@pageindex-1)*@countnum and a.rownum<= @pageindex*@countnum
select @rowcount=COUNT(*) from Student
set @pageindex=234
end

--输出
declare @p int,@c int,@co int
set @p=2
set @c=3
set @co=0
exec usp_GetPageStudnetRowNum3 @p,@c,@co output   --加 output

select @p,@c,@co

--返回总页数

alter proc usp_GetPageStudnetRowNum4

@pageindex int=1,
@countnum int=5,
@rowcount int output,
@pagecount int output
as
begin
select * from
(
select *,ROW_NUMBER() over(order by ID) AS rownum
from Student) as a
where a.rownum >(@pageindex-1)*@countnum and a.rownum<= @pageindex*@countnum
select @rowcount=COUNT(*) from Student
--   set @pagecount=@rowcount/@countnum
set @pagecount=CEILING(CONVERT(float,@rowcount)/CONVERT(float,@countnum))
end

declare @p int,@c int,@co int,@coun int
set @p=2
set @c=3
set @co=0
exec usp_GetPageStudnetRowNum4 @pageindex=@p,@countnum=@c,@rowcount=@co output,@pagecount=@coun output

select @p,@c,@co,@coun as i

--销毁
drop proc usp_GetStudentById

--
select * from
(
select *,ROW_NUMBER() over(order by ID) AS rownum
from Student
) as a
where a.rownum<=5

delete from Student
drop table Studentdrop proc usp_GetStudentById为数据插入学生表创建存储过程

alter  proc INSERE_TO_STUDENT --往student中插入数据
@STUDENT_NAME NVARCHAR(20),
@STUDENT_PWD NVARCHAR(40),
@STUDENT_SEX NVARCHAR(10),
@STUDENT_AGE INT,
@NO int=1

AS
declare @b int
select @b=S_NO FROM S_NO WHERE S_NAME='S_NO'--取出S_NO中S_NO的值

set @b=@b+@NO--让其自加

UPDATE S_NO --将S_NO值修改后在重新放入表中
SET S_NO=@b
WHERE S_NAME='S_NO'
declare @STUDENT_NO NVARCHAR(10)
set @STUDENT_NO= CONVERT(varchar(100), Year(Getdate()))+Convert(NVARCHAR(10),@b)--CONVERT(varchar(100), GETDATE(), 112)为获取当前系统时间

INSERT INTO T_STUDENT(STUDENT_NO,STUDENT_PWD,STUDENT_NAME,STUDENT_SEX,STUDENT_AGE)
VALUES (@STUDENT_NO,@STUDENT_PWD,@STUDENT_NAME,@STUDENT_SEX,@STUDENT_AGE)

为数据插入教师表创建存储过程

alter proc INSERE_TO_TEACHER --往T_TEACHER中插入数据
@NAME NVARCHAR(20),
@PWD NVARCHAR(40),
@SEX NVARCHAR(10),
@TEL NVARCHAR(20),
@N int=1

AS
declare @b int
select @b=T_NO FROM dbo.T_NO WHERE T_NAME='T_NAME'--取出T_NO中T_NO的值

set @b=@b+@N--让其自加

UPDATE T_NO --将S_NO值修改后在重新放入表中
SET T_NO=@b
WHERE T_NAME='T_NAME'
declare @NO NVARCHAR(10)
set @NO= CONVERT(varchar(100), Year(Getdate()))+Convert(NVARCHAR(10),@b)--CONVERT(varchar(100), GETDATE(), 112)为获取当前系统时间

INSERT INTO T_TEACHER(TEACHER_NO,TEACHER_PWD,TEACHER_NAME,TEACHER_SEX,TEACHER_TEL_NO)
VALUES (@NO,@PWD,@NAME,@SEX,@TEL)

为插入管理员对象创建存储过程
CREATE proc INSERE_TO_AMT--往T_TEACHER中插入数据
@NAME NVARCHAR(20),
@PWD NVARCHAR(40),
@N int=1

AS
declare @b int
select @b=A_NO FROM dbo.A_NO WHERE A_NAME='A_NAME'--取出A_NO中A_NO的值

set @b=@b+@N--让其自加

UPDATE A_NO --将A_NO值修改后在重新放入表中
SET A_NO=@b
WHERE A_NAME='A_NAME'
declare @NO NVARCHAR(10)
set @NO= CONVERT(varchar(100), Year(Getdate()))+Convert(NVARCHAR(10),@b)--CONVERT(varchar(100), GETDATE(), 112)为获取当前系统时间

INSERT INTO dbo.T_AMT (AMT_NO,AMT_PWD,AMT_NAME)
VALUES (@NO,@PWD,@NAME)

为查询学生表创建视图
CREATE VIEW SELECT_STUDENT(学号,姓名,密码,性别,年龄)
AS
SELECT STUDENT_NO,STUDENT_NAME,STUDENT_PWD,STUDENT_SEX,STUDENT_AGE FROM dbo.T_STUDENT

为查询管理员表创建视图

CREATE VIEW SELECT_AMT(管理员号,姓名,密码)
AS
SELECT AMT_NO,AMT_NAME ,AMT_PWD FROM dbo.T_AMT
为查询教师表创建视图

CREATE VIEW SELECT_TEACHER(教师号,姓名,密码,性别,电话号码)
AS
SELECT TEACHER_NO,TEACHER_NAME,TEACHER_PWD ,TEACHER_SEX,TEACHER_TEL_NO FROM dbo.T_TEACHER
为查询所有用户的信息建立的视图
CREATE VIEW SELECT_ALL (用户名编号,姓名,密码,权限类型)
AS
SELECT STUDENT_NO,STUDENT_NAME,STUDENT_PWD,LIMM FROM dbo.T_STUDENT
union
SELECT TEACHER_NO,TEACHER_NAME,TEACHER_PWD,LIMM FROM dbo.T_TEACHER
union
SELECT AMT_NO,AMT_NAME,AMT_PWD,LIMM FROM dbo.T_AMT

select *from SELECT_ALL


实例界面



using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data.SqlClient;

namespace 存储过程
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
//我写的带一个参数的存储过程
private void button1_Click(object sender, EventArgs e)
{
string constr = @"Data Source=.\SQLEXPRESS;Initial Catalog=Test;Integrated Security=True";
SqlConnection conn = new SqlConnection(constr);
conn.Open();
SqlCommand cmd = new SqlCommand("usp_GetStudentById", conn);
cmd.CommandType = CommandType.StoredProcedure;   //指定是存储过程
SqlParameter sp = new SqlParameter("@Id", SqlDbType.Int); //指定参数
//     sp.ParameterName = "Id";
//    sp.SqlDbType = SqlDbType.Int;
sp.Value = 2;
cmd.Parameters.Add(sp);

SqlDataReader dr = cmd.ExecuteReader();
if (dr.Read())
{
MessageBox.Show(dr[2].ToString());
}
dr.Close();
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
da.Fill(dt);
foreach (DataRow drr in dt.Rows)
{
MessageBox.Show(drr[0].ToString()+"  "+drr[1].ToString());
}
conn.Close();
}

private void Form1_Load(object sender, EventArgs e)
{
MessageBox.Show("c");
}

//我写的带多个参数的存储过程
private void button2_Click(object sender, EventArgs e)
{
string constr = @"Data Source=.\SQLEXPRESS;Initial Catalog=Test;Integrated Security=True";
SqlConnection conn = new SqlConnection(constr);
conn.Open();
SqlCommand cmd = new SqlCommand("usp_GetPageStudnetRowNum2", conn);
cmd.CommandType = CommandType.StoredProcedure;   //可有可无??
cmd.Parameters.Add(new SqlParameter("@pageindex",1));
cmd.Parameters.Add(new SqlParameter("@countnum", 5));
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
da.Fill(dt);
foreach (DataRow drr in dt.Rows)
{
MessageBox.Show(drr[0].ToString() + "  " + drr[1].ToString());
}
conn.Close();
}

//教程带多个参数的存储过程
private void button3_Click(object sender, EventArgs e)
{
string constr = @"Data Source=.\SQLEXPRESS;Initial Catalog=Test;Integrated Security=True";
SqlConnection conn = new SqlConnection(constr);
conn.Open();
SqlCommand cmd = new SqlCommand("usp_GetPageStudnetRowNum2", conn);
cmd.CommandType = CommandType.StoredProcedure;
SqlParameter[] parms = {
new SqlParameter("@pageindex",SqlDbType.Int,4),
new SqlParameter("@countnum", SqlDbType.Int,4)
};
parms[0].Value = 1;
parms[1].Value = 3;
cmd.Parameters.AddRange(parms);

SqlDataAdapter da = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
da.Fill(dt);
foreach (DataRow drr in dt.Rows)
{
MessageBox.Show(drr[0].ToString() + "  " + drr[1].ToString());
}
conn.Close();
}

//带输出参数的存储过程
private void button4_Click(object sender, EventArgs e)
{
int pageindex = Convert.ToInt32(textBox1.Text.Trim());
int countnum = Convert.ToInt32(textBox2.Text.Trim());

string constr = @"Data Source=.\SQLEXPRESS;Initial Catalog=Test;Integrated Security=True";
SqlConnection conn = new SqlConnection(constr);
conn.Open();
SqlCommand cmd = new SqlCommand("usp_GetPageStudnetRowNum4", conn);
cmd.CommandType = CommandType.StoredProcedure;
SqlParameter[] parms = {
new SqlParameter("@pageindex",SqlDbType.Int),
new SqlParameter("@countnum", SqlDbType.Int),
new SqlParameter("@rowcount",SqlDbType.Int),
new SqlParameter("@pagecount",SqlDbType.Int)
};
parms[0].Value = pageindex;
parms[1].Value = countnum;
parms[2].Direction = ParameterDirection.Output;
parms[3].Direction = ParameterDirection.Output; //设置输出方向  很重要
cmd.Parameters.AddRange(parms);

SqlDataAdapter da = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
da.Fill(dt);
foreach (DataRow drr in dt.Rows)
{
MessageBox.Show(drr[0].ToString() + "  " + drr[1].ToString());
}
MessageBox.Show("一共有行"+cmd.Parameters[2].Value.ToString());  // output 输出值
MessageBox.Show("一共有页"+cmd.Parameters[3].Value.ToString());
conn.Close();
}
}
}


注:本文章属个人学习总结,部分内容参考互联网上的相关文章。 其中如果发现个人总结有不正确的认知或遗漏的地方请评论告知,欢迎交流。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: