sqlserver中在存储过程中写事务

由于对数据的操作经常需要并发,所以在存储过程中使用事务是非常必要的,我经常这样处理:

if (exists (select * from sys.objects where name = ' sp_**** '))

    drop proc sp_****

go

CREATE PROCEDURE sp_****

参数列表....

@out bit=0 output  --输出参数

AS

BEGIN

set nocount on

begin tran
--数据库 增 改 删

if @@rowcount!=0

begin

commit

set @out=1

end

else

begin

rollback

set @out=0

end

set nocount off

END

下面说调用

方法很多:
一、用system.transactions
二、用存储过程,把事务写在存储过程中,在代码中传递参数,调用存储过程。
三、代码:

        public static int ExecuteSqlTran(List<String> SQLStringList)
        {
            using (SqlConnection conn = new SqlConnection(connectionString))
            {
                conn.Open();
                SqlCommand cmd = new SqlCommand();
                cmd.Connection = conn;
                SqlTransaction tx = conn.BeginTransaction();
                cmd.Transaction = tx;
                try
                {
                    int count = 0;
                    for (int n = 0; n < SQLStringList.Count; n++)
                    {
                        string strsql = SQLStringList[n];
                        if (strsql.Trim().Length > 1)
                        {
                            cmd.CommandText = strsql;
                            count += cmd.ExecuteNonQuery();
                        }
                    }
                    tx.Commit();
                    return count;
                }
                catch
                {
                    tx.Rollback();
                    return 0;
                }
            }
        }

另外有单独介绍sqlserver存储过程的文章,写得不错

http://www.cnblogs.com/hoojo/archive/2011/07/19/2110862.html

原文地址:https://www.cnblogs.com/ygyxinyu/p/2919426.html