使用SQL Server Schema Comparion新增NOT NULL欄位

使用SQL Server Schema Comparion新增NOT NULL欄位

我們的資料庫除了正式區之外都是使用 Visual Studio 資料庫專案來進行版控與管理。在測試區碰到一個簡單需求,新增表格欄位,例如定義 LocationType NVARCHAR (50) NOT NULL,透過 New Schema Comparion 原本以為快速就能解決的表格更新,結果立刻得到如下錯誤:

\*\* Warnings
     The column [dbo].[dbname].[LocationType] on table [dbo].[dbname] must be added, but the
       column has no default value and does not allow NULL values. If the table contains data, the ALTER script will not work.
       To avoid this issue you must either: add a default value to the column, mark it as allowing NULL values, or enable the
       generation of smart-defaults as a deployment option.

\*\* Highlights
     Tables that will be rebuilt
       [dbo].[dbname]
     Clustered indexes that will be dropped
       None
     Clustered indexes that will be created
       None
     Possible data issues
       The column [dbo].[dbname].[LocationType] on table [dbo].[dbname] must be added, but the
         column has no default value and does not allow NULL values. If the table contains data, the ALTER script will not work.
         To avoid this issue you must either: add a default value to the column, mark it as allowing NULL values, or enable the
         generation of smart-defaults as a deployment option.

\*\* User actions
     Table rebuild
       [dbo].[dbname] (Table)

\*\* Supporting actions
     Drop ...
     Create ...
     Refresh ...

錯誤原因很簡單,要更新的測試資料表已含有歷史測試資料,你加入一個 NOT NULL 欄位,但舊 Row 的新欄位會是 NULL。詢問同事,學習到這種更新 NOT NULL 需求,基本上有四個步驟:

  1. 設定 Update Script 欄位為 NULL
  2. 更新 Table,加入新欄位
  3. 更新新欄位為 '' (空白)
  4. 更新 Update Script 為 NOT NULL

以上步驟執行上沒有任何問題。

不過,錯誤訊息裡的一句話引起我的好奇「enable the generation of smart-defaults as a deployment option.」查詢了 Schema Comaprion 設定:

smart-defaults

測試了一下,嗯…它就是幫我們做1, 2, 3, 4那四個步驟(我認為啦,因為結果是一模一樣),原來我們做的是一件 smart 的事(開心)。現在,你可以選擇自己手動做 smart-defaults 或由 Schema Comaprion 來幫你做都行。

5 則留言:

  1. 其實也可以用這樣的 script :
    ALTER TABLE [dbo].[dbname]
    ADD LocationType NVARCHAR (50) NOT NULL CONSTRAINT DF_DBNAME_LOCATIONTYPE DEFAULT '';
    GO;
    --DROP CONSTRAINT DF_DBNAME_LOCATIONTYPE; --通常我是不會拿掉預設值
    GO;

    回覆刪除
  2. 你好,剛才有留意到你放上YOUTUBE的影片:bootstrap 教學https://www.youtube.com/watch?v=Na6BxyUXeFk&t=3116s
    其中我覺得你的kkbruce.tw網頁寫得很好,但現在似乎連接不上,是否關閉了...

    回覆刪除

感謝您的留言,如果我的文章你喜歡或對你有幫助,按個「讚」或「分享」它,我會很高興的。