How to change a column without dropping a table in SQL 2008

前端 未结 5 465
执笔经年
执笔经年 2021-01-31 02:01

Why does SQL 2008 all of a sudden want to drop my tables when I go to change the column type from say int to real? This never happened in SQL 2005 to my knowledge. Any insight

5条回答
  •  一个人的身影
    2021-01-31 02:36

    Here is what I use:

    -- Add new column
    ALTER TABLE MyTable
    ADD Description2 VARCHAR(MAX)
    GO
    
    -- Copy data to new column (probably with modifications)
    Update MyTable
    SET Description2 = Description
    GO
    
    -- Drop old column
    ALTER TABLE MyTable
    DROP COLUMN Description
    GO
    
    -- Rename new column to the original column's name.
    sp_RENAME 'MyTable.Description2' , 'Description', 'COLUMN'
    GO
    
    1. Copy the data into a new column.
    2. Drop the old column.
    3. Rename the new column to the old column's name.

提交回复
热议问题