Giả sử bạn có bảng sản phẩm với các thông tin như sau:
- create table Product
- (
- ProductID int not null primary key identity,
- ProductName varchar (50) not null,
- Description varchar(1000) not null,
- Price money
- )
Thủ tục sử dụng để lưu thông tin một sản phẩm vào cơ sở dữ liệu có thể viết theo một trong hai cách sau:
- create procedure spInsertProduct
- (
- -- Khai báo biến, biến này phải có kiểu dữ liệu giống như trong CSDL
- @name varchar(50),
- @description varchar(1000),
- @price money
- -- Biến trả về kết quả thực thi
- @result int output
- )
- as
- begin transaction
- insert into Product (ProductName, Description, Price ) values(@name,@description,@price)
- if @@ERROR <> 0
- begin
- -- Có lỗi xảy ra, rollback transaction
- set @result=0
- ROLLBACK
- end
- else
- begin
- -- Thành công! commit the transaction
- set @result=1
- COMMIT
- end
hoặc
- create procedure spInsertProduct
- (
- -- Khai báo biến, biến này phải có kiểu dữ liệu giống như trong CSDL
- @name varchar(50),
- @description varchar(1000),
- @price money
- -- Biến trả về kết quả thực thi
- @result int output
- )
- as
- begin try
- begin transaction
- insert into Product (ProductName, Description, Price ) values
- (@name,@description,@price)
- --Nếu chạy đến câu lệnh tiếp theo --> thực thi thành công
- set @result=1
- COMMIT
- end try
- begin catch
- if @@TRANCOUNT > 0
- begin
- -- Có lỗi xảy ra, rollback transaction
- set @result=0
- ROLLBACK
- end
- end catch
Trong phần mã C# ứng dụng, bạn thực hiện gọi thực thi thủ tục và kiểm tra kết quả trả về:
- // strConn is your connection string
- SqlConnection cn = new SqlConnection(strConn);
- SqlCommand cmd = cn.CreateCommand();
- cmd.CommandText = "spInsertProduct";
- cmd.CommandType = CommandType.StoredProcedure;
- cmd.Parameters.Add("@name", SqlDbType.VarChar, 50);
- cmd.Parameters["@name"].Direction = ParameterDirection.Input;
- cmd.Parameters["@name"].Value = txtName.Text;
- cmd.Parameters.Add("@description", SqlDbType.VarChar, 1000);
- cmd.Parameters["@description"].Direction = ParameterDirection.Input;
- cmd.Parameters["@description"].Value = txtDescription.Text;
- cmd.Parameters.Add("@result", SqlDbType.Int);
- cmd.Parameters["@result"].Direction = ParameterDirection.ReturnValue;
- cn.Open();
- cmd.ExecuteNonQuery();
- cn.Close();
- int result = Convert.ToInt32(cmd.Parameters["@result"].Value);
- // kiểm tra giá trị trả về
- if(result==1)
- MessageBox.Show("Success");
- else
- MessageBox.Show("Error");
No comments:
Post a Comment