简体   繁体   English

SQL Server如何处理UPDATE事务?

[英]How SQL Server handles UPDATE transactions?

We have a table which is used to Generate Unique Numeric keys. 我们有一个用于生成唯一数字键的表。 These keys are then used as a PrimaryKey in other tables. 这些键然后在其他表中用作PrimaryKey。 Table structure is like this: 表结构是这样的:

TableName     VARCHAR
CurrentKey    INT

So we have data in this table like 所以我们在这个表中有数据

TableName   Customers
CurrentKey  400

So when we need next primary key for table Customers we get the CurrentKey from this table where TableName is Customers , it will give us 400 we increment (400+1) it and we update this key in the table also. 因此,当我们需要表Customers下一个主键时,我们从表中获取CurrentKey ,其中TableNameCustomers ,它将给我们增加400,我们将其递增(400 + 1),并在表中也更新此键。 So our CurrentKey is 401 now. 所以我们的CurrentKey现在是401。

The sql we use for this purpose is: 我们用于此目的的sql是:

SQL1: SQL1:

DECLARE  @CurrentKey INT
UPDATE  myTable 
SET @CurrentKey = CurrentKey = CurrentKey + 1
WHERE   TableName = @TableName

My question is that Do we need to LOCK the table so that the keys may not duplicate if multiple users call this at the same time? 我的问题是,是否需要锁定表,以便如果多个用户同时调用此键,则键可能不会重复? i am sure that SQL Server will not allow duplicate data but i don't know HOW... Query with Table Lock: 我确定SQL Server将不允许重复数据,但我不知道该如何...使用表锁查询:

SQL2 SQL2

BEGIN TRANSACTION
    DECLARE  @CurrentKey INT
    UPDATE  myTable WITH (TABLOCKX)
    SET @CurrentKey = CurrentKey = CurrentKey + 1
    WHERE   TableName = @TableName
END TRANSACTION

Can someone please explain how the SQL Server handles UPDATE calls? 有人可以解释一下SQL Server如何处理UPDATE调用吗?

Each SQL statement runs in a transaction, and an update statement always uses a lock to protect its update. 每个SQL语句都在事务中运行,并且update语句始终使用锁来保护其更新。 SQL Server does not allow you to read a half-modified row (with some exceptions for data that is larger than 8k.) SQL Server不允许您读取半修改的行(某些例外情况是大于8k的数据。)

Your first statement should be fine. 您的第一句话应该没问题。

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

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