Thursday, July 30, 2009

Sql Transaction with stored procedure

create two table first and create stored procedure

create table emp(emp_id int , empname varchar(25));
create proc emp1
@emp_id int ,
@empname varchar(25)
as
begin
insert into emp values(@emp_id,@empname)
end

create table emp_detail (emp_id int ,city varchar(25));
create proc emp2
@emp_id int,
@city varchar(25)
as
begin
insert into emp_detail values (@emp_id,@city)
end

Then write this code
protected void Button1_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection("data source=.;
initial catalog =abhishek;uid=sa; pwd=computer");
con.Open();
SqlTransaction st;
st = con.BeginTransaction("First");


SqlCommand cmd1 = new SqlCommand();
cmd1.Transaction = st;

try
{

cmd1.Parameters.Add("@emp_id", SqlDbType.Int).Value =
TextBox1.Text;
cmd1.Parameters.Add("@empname", SqlDbType.VarChar, 25).Value =
TextBox2.Text;
cmd1.CommandText = "emp1";
cmd1.CommandType = CommandType.StoredProcedure;
cmd1.Connection = con;

cmd1.ExecuteNonQuery();

cmd2 = new SqlCommand();
cmd2.Transaction = st;

cmd2.Parameters.Add("@emp_id", SqlDbType.Int).Value
= TextBox1.Text;
cmd2.Parameters.Add("@city", SqlDbType.VarChar, 25).Value
= TextBox3.Text;
cmd2.Connection = con;

cmd2.CommandText = "emp2";
cmd2.CommandType = CommandType.StoredProcedure;
cmd2.ExecuteNonQuery();
st.Commit();
}
catch(Exception ex)
{
st.Rollback();
Response.Write(ex.Message.ToString());
}
}

0 comments:

Post a Comment

plzz give the comment