.NET - 棘手的SQL事务(SQL Server中,但甲骨文在心中也为更高版本) [英] .net - tricky sql transaction (SQL Server, but Oracle in mind too, for later)

查看:186
本文介绍了.NET - 棘手的SQL事务(SQL Server中,但甲骨文在心中也为更高版本)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我要执行批量操作布尔AddEntitiesX(名单其中,X>)

  • X 的每一个INSERT INTO X_Table (用 X_UID 为自动递增ID),我需要插入的 K -times另一个实体 Y_Table (用 X_UID FK Y_UID 为自动递增ID) ,因为 X 包含一系列的 K - 实体
  • 然后,对于每个插入 X ,我也需要插入以Z 实体 Z_Table (用 X_UID FK Z_UID 作为自动递增ID)。
  • For each insert of X into X_Table (with X_UID as auto-increment ID), I have to insert k-times another entity Y into Y_Table (with X_UID as FK and Y_UID as auto-increment ID), since X contains a list of k-Y entities.
  • Then, for each inserted X, I need to insert also a Z entity in Z_Table (with X_UID as FK and Z_UID as auto-increment ID).

我的伪code将是这样的:

My pseudo-code will look like this:

// cannot use 'TransactionScope' since there are problems with Oracle
// so, prepare SqlTransaction
foreach (X)
{
 //1. call 'InsertX' SP

 foreach (Y in x.ListY)
   //2. call 'InsertY' SP

 //3. call 'InsertZ' SP
}
// commit transaction

我怎样才能找回 X_UID InsertX SP传递到下一个存储的特效?

How can I retrieve the X_UID from InsertX SP to pass to the next stored procs?

如果没有办法,然后因为我不能有一个存储过程,这个大交易,我应该怎么模拟呢?

If there is no way, then since I cannot have this big transaction in one stored procedure, how should I model it?

我想知道的最佳做法,以使用事务从业务处理这类业务的数据层。

I would like to know best practices to handle this kind of operations from business to data layer using transactions.

感谢您......并请让我知道,如果我的问题不够清楚。

Thank you... and please let me know if my question is not clear enough.

推荐答案

一种方法是使用的 SCOPE_IDENTITY() ,像正保远程教育已经建议。另一种方法是使用INSERT的 OUTPUT子句

INSERT INTO table (field, field, ...) 
OUTPUT INSERTED.ID
VALUES (@value, @value, ...);

这个插入的记录,也产生一个结果集,其中包含插入生成的行标识值。在C#中,你读到这个结果集,就好像你已经执行SELECT,即。您使用 的ExecuteReader()

This inserts the record and also produces a result set, which contains the inserted row generated identity value. In C# you read this result set just as if you'd have executed a SELECT, ie. you use ExecuteReader().

使用OUTPUT子句的一个优点是它可以可靠回报的的行ID的唯一途径。说你插入不是一个,而是100,就可以取回所有100插入行的ID在一个单一的结果集。如果你想知道如何插入100行一举,请参见阵列和SQL列表Server 2008中:使用表值参数

One advantage of using OUTPUT clause is that is the only way it can reliable return multiple row IDs. Say you insert not one, but 100, you can get back the IDs of all 100 inserted rows in a single result set. In case you wonder how to insert 100 rows in one swoop, see Arrays and Lists in SQL Server 2008: Using Table-Valued Parameters.

使用OUTPUT子句的另一个好处是,你可以链的两个语句到一个单一的,看的链接的更新

Another advantage of using OUTPUT clause is that you can chain two statements into a single one, see Chained Updates.

这篇关于.NET - 棘手的SQL事务(SQL Server中,但甲骨文在心中也为更高版本)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆