没有其他命令的执行在执行2 SQL正确的方式命令 [英] Correct way to execute 2 SQL commands without other command executing in between

查看:113
本文介绍了没有其他命令的执行在执行2 SQL正确的方式命令的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

建议的重复不会回答标题的问题。

我要执行两个没有任何其他的用户MSSQL命令(我不知道什么是正确的说法),它们之间执行的命令。

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. 使用TABLOCK。 - 但我已经看到了它被认为是不好的做法

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

使用一个交易 - 但是,所有我能找到的是,这将是原子, 的,不一定把其它行动。

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.

编辑:我想插入一行,并得到其身份。 (这似乎不是简单,因为我期望的那样。)

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

推荐答案

要插入一行,并获得其身份,你并不需要阻止其他所有的命令。只需使用组合的事务与 SCOPE_IDENTITY

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;

更多关于 SCOPE_IDENTITY MSDN

这篇关于没有其他命令的执行在执行2 SQL正确的方式命令的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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