alter table的SQL Server性能改变列更改数据类型

Sha*_*bie 5 sql sql-server performance

我们需要将某些列的数据类型从int更改为bigint.不幸的是,其中一些表很大,大约有7到1000万行(但不是很宽).

Alter table alter column将永远占用这些表.有没有更快的方法来实现这一目标?

Mat*_*att 8

巧合的是,我必须在3个小时前做一些非常相似的事情.这个表是35米的行,它是相当宽的,它是永远需要做到这一点:

alter table myTable add myNewColumn int not null default 0;
Run Code Online (Sandbox Code Playgroud)

这就是我最终的目标:

alter table myTable add myNewColumn int null;

while 1=1
begin
    update top (100000) myTable
    set
        myNewColumn = 0
    where
        myNewColumn is null;

    if @@ROWCOUNT = 0 break;
end

alter table myTable alter column myNewColumn int not null;
alter table myTable add constraint tw_def_myNewColumn default (0) for myNewColumn;
Run Code Online (Sandbox Code Playgroud)

这一次,alter table声明几乎是即时的.这需要大约7-8分钟(在慢速服务器上)进行更新批处理.我猜测SQL Server正在我的原始查询中生成撤消以恢复值,但我没想到开始.

无论如何,在你的情况下,也许类似的东西会有所帮助.您可以尝试添加新的bigint列,批量更新新列,然后在其上设置约束.