简体   繁体   English

SQLServer如何处理Alter Table命令?

[英]How the Alter Table command is handled by SQLServer?

We are using SQL Server 2008. We have an Existing database and it was required to ADD a new COLUMN to one of the Table which has 2700 rows only but one of its column is of type VARCHAR(8000) . 我们使用SQL Server 2008中,我们有一个现有的数据库,并要求它ADD了新的COLUMN到一个Table它只有2700行 ,但其列的一个类型是VARCHAR(8000) When i try to add new column ( CHAR(1) NULL ) by using ALTER table command, it takes too much time!! 当我尝试使用ALTER table命令添加新列( CHAR(1) NULL )时,它花费了太多时间! it took 5 minutes and the command was still running to i stopped the command. 花了5分钟 ,命令仍然在运行,我停止了命令。 Below is the command, i was trying to add new column: 下面是命令,我试图添加新列:

ALTER TABLE myTable Add ColumnName CHAR(1) NULL
  1. Can someone help me to understand that How the SQL Server handles the ALTER Table command? 有人可以帮助我了解SQL Server如何处理ALTER Table命令吗? what happens exactly? 到底会发生什么?
  2. Why it takes so much time to Add new column 为什么要花这么多时间来添加新列

EDIT : 编辑

  1. What is the effect of Table size on ALTER Command ? 表大小ALTER Command有什么影响?

Altering a table requires a schema lock. 更改表需要模式锁。 Many other operations require the same lock too. 许多其他操作也需要相同的锁。 After all, it wouldn't make sense to add a column halfway a select statement. 毕竟,在select语句的中间添加一列是没有意义的。

So a likely explanation is that a process had the table locked for 5 minutes. 因此,一个可能的解释是一个进程将表锁定了5分钟。 The ALTER then has to wait until it gets the lock itself. 然后, ALTER必须等到它自己获得锁为止。

You can see blocked processes, and the blocking process, from the Activity Monitor in SQL Server Management Studio. 您可以从SQL Server Management Studio中的“活动监视器”查看被阻止的进程以及被阻止的进程。

Well, one thing to bear in mind is that you were adding a new fixed length column to the table. 好吧,要记住的一件事是您正在向表中添加新的固定长度列。 The way that rows are structured in storage, all fixed length columns are placed before all of the variable length columns, for each row. 在存储中行的结构方式中,对于每行,所有固定长度的列都位于所有可变长度的列之前。 So every row would have had to be updated in storage to make this change. 因此,必须对存储中的每一行进行更新才能进行此更改。

If, in turn, this caused the number of rows which could be stored on each page to change, a great many new allocations may have been required. 如果这进而导致可以存储在每个页面上的行数发生更改,则可能需要大量新分配。

That being said, for the number of rows indicated, I wouldn't have though it should take 5 minutes - unless, as Andomar indicated, there was some lock contention also involved. 话虽如此,对于所示的行数,我将不必花5分钟的时间-除非像Andomar指出的那样,还涉及一些锁争用。

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

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