简体   繁体   English

如何防止SQL同时运行事务

[英]How do I prevent SQL from running transactions simultaneously

I've noticed that MS SQL may begin another transaction just before a previous transaction is complete (or committed). 我注意到,MS SQL可能在上一个事务完成(或提交)之前开始另一个事务。 Is there a way how we can ensure a transaction must complete first before the next transaction begins? 有什么方法可以确保交易必须在下一个交易开始之前先完成?

My problem is that I want to perform an SQL SELECT almost immediately after an SQL INSERT. 我的问题是我想在执行SQL INSERT之后几乎立即执行SQL SELECT。 What I'm seeing right now is; 我现在看到的是 when the SELECT statement is run; 当SELECT语句运行时; it does not return the (very) recently inserted data. 它不返回(非常)最近插入的数据。

As I traced this scenario using SQL profiler, I've noticed that the SQL INSERT and SELECT performs simultaneously, as in the SELECT occurs before the INSERT is completed. 当我使用SQL事件探查器跟踪这种情况时,我注意到SQL INSERT和SELECT同时执行,就像SELECT在INSERT完成之前发生一样。

Is there a way to fix this problem of mine? 有没有办法解决我的这个问题? thanks! 谢谢!

From the sounds of it, you're looking for the OUTPUT clause 从声音上看,您正在寻找OUTPUT子句

From the examples in the documentation http://msdn.microsoft.com/en-us/library/ms177564.aspx 从文档http://msdn.microsoft.com/zh-cn/library/ms177564.aspx中的示例中

DECLARE @MyTableVar table( NewScrapReasonID smallint,
                           Name varchar(50),
                           ModifiedDate datetime);
INSERT Production.ScrapReason
    OUTPUT INSERTED.ScrapReasonID, INSERTED.Name, INSERTED.ModifiedDate
        INTO @MyTableVar
VALUES (N'Operator error', GETDATE());

You can run your transactions in SERIALIZABLE isolation level. 您可以在SERIALIZABLE隔离级别中运行事务。 In this way you will ensure that the select will be performed after the insert. 这样,您将确保在插入后执行选择。 In lower isolation levels, the select is performed in paralell and returns the snapshot of the data - the way it is seen with all transactions completed before the one that issues select has been started. 在较低的隔离级别中,选择是在paralell中执行的,并返回数据的快照-在开始执行发出选择的事务之前,已完成所有事务的处理方式。

I'm guessing you want to get an auto-generated identifier back after the insert? 我猜您想在插入后找回自动生成的标识符? I'm not sure the MSSQL way to do this, but in PostgreSQL, there is INSERT ... RETURNING extension to solve exactly this problem. 我不确定使用MSSQL的方式,但是在PostgreSQL中,有INSERT ... RETURNING扩展来解决这个问题。

http://www.postgresql.org/docs/9.1/static/sql-insert.html http://www.postgresql.org/docs/9.1/static/sql-insert.html

Are you locked into MSSQL? 您是否已锁定MSSQL?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM