Time to add default values to a new column by approach

我的梦境 提交于 2019-12-25 03:08:38

问题


I need to add a new non-null column to an existing SQL table and set it to a default value. I understand that there are two different approaches to this:

  1. ALTER TABLE Foo ADD Col CHAR(1) NOT NULL DEFAULT('N')

  2. ALTER TABLE Foo ADD Col CHAR(1) GO UPDATE Foo SET Col = 'N' GO ALTER TABLE Foo ALTER COLUMN Col CHAR(1) NOT NULL DEFAULT('N')

That is, in the second approach, there are three separate batches: first the column is created, then the default value is backfilled, and then the not null constraint and the default value is added.

One of the devs around here has asserted that the second approach is faster, results in less time with a lock, and that approach #1 results in a huge log. I have been trying to reproduce this, but haven't been able to yet. It could be that my sample dataset is too small, and what he's describing is only apparent on large DBs, or with particular schemata.

Rather than spending the time to generate increasingly large datasets and repeatedly modify the schema, I figured I would turn to the experts here and get the skinny. Is the second approach actually better for large datasets?


回答1:


So I've decided to test that.
On Sql server 2012, It took less then a second to perform the first alter table on a table that has more then 13.6 million records.

For the second approach, it took 49 seconds, so I would say that your dev is wrong.



来源:https://stackoverflow.com/questions/30356453/time-to-add-default-values-to-a-new-column-by-approach

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