一聚教程网:一个值得你收藏的教程网站

最新下载

热门教程

Sqlserver 存储过程 事务实例代码

时间:2010-06-13 编辑:简简单单 来源:一聚教程网


--方式一
if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[USP_ProcedureWithTransaction_Demo]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[USP_ProcedureWithTransaction_Demo]
GO
-- =============================================
-- Author:
-- Create date: <2010-06-11>
-- Description:
-- =============================================
Create PROCEDURE [dbo].[USP_ProcedureWithTransaction_Demo]
As
Begin
SET XACT_ABORT ON
Begin Transaction
Insert Into Lock(LockTypeID) Values('A')--此语句将出错,LockTypeID为Int类型
Update Lock Set LockTypeID = 2 Where LockID = 32
Commit Transaction
SET XACT_ABORT OFF
End
GO 

 

--方式二
if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[USP_ProcedureWithTransaction_Demo]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[USP_ProcedureWithTransaction_Demo]
GO
-- =============================================
-- Author:
-- Create date: <2010-06-11>
-- Description:
-- =============================================
Create PROCEDURE [dbo].[USP_ProcedureWithTransaction_Demo]
As
Begin
Begin Transaction
Insert Into Lock(LockTypeID) Values('A')--此语句将出错,LockTypeID为Int类型
Update Lock Set LockTypeID = 1 Where LockID = 32
Commit Transaction
If(@@ERROR <> 0)
Rollback Transaction
End
GO

--方式三
if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[USP_ProcedureWithTransaction_Demo]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[USP_ProcedureWithTransaction_Demo]
GO
-- =============================================
-- Author:
-- Create date: <2010-06-11>
-- Description:
-- =============================================
Create PROCEDURE [dbo].[USP_ProcedureWithTransaction_Demo]
As
Begin
Begin Try
Begin Transaction
Update Lock Set LockTypeID = 1 Where LockID = 32--此语句将出错,LockTypeID为Int类型
Insert Into Lock(LockTypeID) Values('A')
Commit Transaction
End Try
Begin Catch
Rollback Transaction
End Catch
End
GO

Exec [USP_ProcedureWithTransaction_Demo]


///


/// 批量执行SQL语句
///

/// SQL语句数组
/// SQL参数对象数组
///
public static Int32 ExecuteSqls(String[] Sqlstr, List param)
{
String ConnStr = GetSqlConnection();
using (SqlConnection conn = new SqlConnection(ConnStr))
{

SqlCommand cmd = new SqlCommand();
SqlTransaction tran = null;
cmd.Transaction = tran;
try
{
conn.Open();
tran = conn.BeginTransaction();
cmd.Connection = conn;
cmd.Transaction = tran;

Int32 count = Sqlstr.Length;
for (Int32 i = 0; i < count; i++)
{
cmd.CommandText = Sqlstr[i];
cmd.Parameters.AddRange(param[i]);
cmd.ExecuteNonQuery();
}
tran.Commit();
return 1;
}
catch
{
tran.Rollback();
return 0;
}
finally
{
cmd.Dispose();
conn.Close();
}
}
}

热门栏目