问题
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:
ALTER TABLE Foo ADD Col CHAR(1) NOT NULL DEFAULT('N')
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