In this example, there is a table in the database named StudentTable
. There are 5 columns in the table, namely
Id int,
StudentName nvarchar(50),
StudentNumber nvarchar(20),
Age int,
Class nvarchar(50) The
stored procedure codes are as follows, including New, deleted, and modified functions:
USE [MySqlDataBase] --我的数据库名为MySqlDataBase,添加这行表示在MySqlDataBase数据库中执行下面代码
GO
if exists (select * from sysobjects where id = object_id(N'PROC_UpdateTable') and type in (N'P', N'PC'))
drop procedure PROC_UpdateTable --在数据库中执行本文件代码的时候,如果存在名为PROC_UpdateTable的存储过程则将旧的存储过程删除
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author: Bruce
-- Description: 操作表格
-- =============================================
CREATE PROCEDURE [dbo].[PROC_UpdateTable](
@OperType int, --操作类型(0-不操作,1-新增,2-删除,3-修改
@Id int,
@StudentName nvarchar(50),
@StudentNumber nvarchar(20),
@Age int,
@Class nvarchar(50)
)--本存储过程包含上述参数,可以由客户端程序将参数传给本存储过程
AS
declare @maxid int
BEGIN
--使返回的结果中不包含有关受 Transact-SQL 语句影响的行数的信息
SET NOCOUNT ON;
--如果外部存在事务则不执行存储过程
if((@@trancount<>0) or (@OperType = 0))
return 1
--如果 Transact-SQL 语句产生运行时错误,整个事务将终止并回滚
set xact_abort on
if(@OperType = 1) --新增
begin
begin tran maintran
insert into StudentTable values(@StudentName,@StudentNumber,@Age,@Class);
if(@@ERROR <> 0)
begin
rollback tran maintran
return 4 -- 失败,回滚
end
commit tran miantran
return 0
end
else if(@OperType = 2) --删除
begin
begin tran maintran
delete from StudentTable where ID=@Id;
if(@@ERROR <> 0)
begin
rollback tran maintran
return 4 -- 失败,回滚
end
commit tran miantran
return 0
end
else if(@OperType = 3) --修改
begin
begin tran maintran
update StudentTable set StudentName=@StudentName,StudentNumber=@StudentNumber,Age=@Age,Class=@Class where ID=@Id;
if(@@ERROR <> 0)
begin
rollback tran maintran
return 4 -- 失败,回滚
end
commit tran miantran
return 0
end
END