行为存储过程(23)

行为存储过程适用于执行某些数据库功能,但不返回记录或值。这些数据库功能包括对数据的更新、编辑和修改、
下面通过一个行为存储过程实习成绩表grade中插入一天新的记录和功能,定义了@stud_id、参数@course和@score、在向表中插入时,
需要先判断表中是否有相同的记录。如果存在 则不插入该记录,并给出相应的提示信息,否则插入该记录。
存储过程add_grade的代码如下:
create procedure add_grade
@stud_id char(9),
@course varchar(50),
@score int
as
declare @recordcount int
set @recordcount=
(
select count(*) from grade
where stud_id=@stud_id and
course=@course
)
if @recordcount<1
begin
insert into grade
values(@stud_id,@course,@score)
end

然后在编辑的页面编写如下代码

~~~~~~~~~~~
 using System.Data.SqlClient;
namespace 行为存储过程
{
public partial class _Default : System.Web.UI.Page
{
override protected void OnInit( EventArgs e)
{
InitializeComponent();
base.OnInit(e);
}

private void InitializeComponent()
{
this.Button1.Click += new System.EventHandler
(this.Button1_Click);
}

protected void Button1_Click(object sender, EventArgs e)
{
string conncetionstring = "Data Source=神舟龙-PC\\SQLEXPRESS;Initial Catalog=student;Integrated Security=True;";
SqlConnection conn=new SqlConnection (conncetionstring);
SqlCommand comm=new SqlCommand ("add_grade",conn);//调用已经定义好的add_grade存储过程
comm.CommandType=CommandType.StoredProcedure;
comm.Parameters.Add(new SqlParameter("@stu_id",this.TextBox1.Text));
comm.Parameters.Add(new SqlParameter("@course",this.TextBox2.Text));
comm.Parameters.Add(new SqlParameter("@score",this.TextBox3.Text));
try
{
conn.Open();
comm.ExecuteNonQuery();//调用comm对象的ExecuteNonQuery方法来执行存储过程以添加学生成绩,并给出操作提示。
this.Page.RegisterStartupScript("message", "<script>alert('添加成功')</script>");//代码有点过时了!汗,以后争取不出现这种情况
}
catch
{
this.Page.RegisterStartupScript("message","<script>alert('添加失败')</script>");
}
finally
{
conn.Close();
}
}



}
}

通过调用存储过程,不仅速度快,安全性高,而且调试容易,特别是复杂的商业逻辑操作,使用存储过程不仅容易实现,而且大大减少代码编程量,更加体现存储过程的优势。

神舟龙

原文地址:https://www.cnblogs.com/shenzhoulong/p/1743939.html