Update ANSI_NULLS option in an existing table

后端 未结 3 1769
独厮守ぢ
独厮守ぢ 2021-01-08 00:44

In our database there is a table which is created with ANSI_NULLS OFF. Now we have created a view using this table. And we want to add a clustered index for thi

3条回答
  •  生来不讨喜
    2021-01-08 01:01

    Unfortunately, there is no way how to do it without recreating. You need to create new table with ANSI_NULLS ON and copy there all data.

    It should be something like:

    SET ANSI_NULLS ON;
    
    CREATE TABLE new_MyTBL (
    ....
    )
    
    -- stop all processes changing your data at this point
    
    SET IDENTITY_INSERT new_MyTBL ON
    
    INSERT new_MyTBL (...)   -- including IDENTITY field 
    SELECT ...               -- including IDENTITY field 
    FROM MyTBL 
    
    SET IDENTITY_INSERT new_MyTBL OFF
    
    -- alter/drop WITH SCHEMABINDING objects at this point
    
    EXEC sp_rename @objname = 'MyTBL', @newname = 'old_MyTBL'
    EXEC sp_rename @objname = 'new_MyTBL', @newname = 'MyTBL'
    
    -- alter/create WITH SCHEMABINDING objects at this point
    -- re-enable your processes
    
    DROP TABLE old_MyTBL      -- do that when you are sure that system works OK
    

    If there are any depending objects, they will work with new table as soon as you rename it. But if some of them are WITH SCHEMABINDING you need to DROP and CREATE them manualy.

提交回复
热议问题