Correct way to execute 2 SQL commands without other command executing in between

有些话、适合烂在心里 提交于 2020-01-04 15:30:02

问题


The suggested duplicate doesn't answer the question in the title.

I want to execute two MSSQL commands without any other "user" (I'm not sure what's the correct term) executing a command between them.

Searching, I have found two ways that seem like they would achieve that but am unsure about them:

  1. Use TABLOCK. - But I've seen it being considered bad practice.

  2. Use a transaction - But all I could find was that it will be atomic, and not necessarily locking out other actions.

What way is the correct way?

More info: Only my program will be accessing the database, but it might be from several instances of it, and I don't mind a short wait - if one instance will have to wait in line for a second or two - that's fine.

EDIT: I'm trying to insert a row and get its identity. (It seems not to be straightforward as I would expect.)


回答1:


To insert a row and get its identity, you don't need to block all other commands. Just use a transaction in combination with SCOPE_IDENTITY:

BEGIN TRAN;

INSERT INTO MyTable (MyColumn)
VALUES ('MyValue');

SELECT SCOPE_IDENTITY();

COMMIT TRAN;

More on SCOPE_IDENTITY at MSDN.




回答2:


You need to use a Transaction with an IsolationLevel of Serializable. That will prevent other users reading or modifying the rows used by the query for the duration of the transaction without completely locking out the table.




回答3:


You can not prevent commands from being executed in between two other commands. All you can do is prevent data from being modified until you're finished with modifying it yourself. This is done using transactions using the respective isolation level.



来源:https://stackoverflow.com/questions/16016636/correct-way-to-execute-2-sql-commands-without-other-command-executing-in-between

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!