我有一個大表中的持久化計算列在SQL Server 2005中轉換的計算列專欄
我想將其轉換爲常規列,保持當前值。
我是否需要重新創建列並更新事務中的整個表, 或者是否可以更改計算列規範以及如何執行?
我有一個大表中的持久化計算列在SQL Server 2005中轉換的計算列專欄
我想將其轉換爲常規列,保持當前值。
我是否需要重新創建列並更新事務中的整個表, 或者是否可以更改計算列規範以及如何執行?
-- Create a new Column (unpersisted):
ALTER TABLE MyTable
ADD newColumn DatatypeOfPersistedColumn
GO
UPDATE myTable
SET newColumn = PersistedColumn
GO
-- Delete the persisted column
ALTER TABLE MyTable
DROP COLUMN PersistedColumn
GO
-- Rename new column to old name
EXEC sp_rename 'MyTable.newColumn', 'PersistedColumn', 'COLUMN'
GO
我需要保留列的名稱。 – 2010-11-12 11:13:01
然後使用EXEC sp_rename'newColumn','PersistedColumn','COLUMN'刪除PersistedColumn後重命名 – IDisposable 2011-02-03 22:28:11
距離「計算列規格」中SSMS表中的德興模式刪除公式。值將保持原樣。
這種方式管理工作室實際上重新創建表並重新插入值。這是一個大型的生產數據庫,所以它不適合我。 – 2010-11-10 12:24:22
假設將計算列轉換爲「真實」列的原因是您希望保留現有值/功能,但添加了在需要時覆蓋它的功能,您可以添加一個新列(將僅在現有派生值將被覆蓋的位置填充),並將計算列的定義更改爲COALESCE(NewColumn,
舊計算定義)
。
-- Create a new Column (unpersisted):
ALTER TABLE MyTable
ADD newColumn DatatypeOfPersistedColumn
UPDATE myTable
SET newColumn = PersistedColumn
-- Delete the persisted column
ALTER TABLE MyTable
DROP COLUMN PersistedColumn
-- Rename the new column to the old name
EXEC sp_rename 'MyTable.newColumn', 'PersistedColumn', 'COLUMN'
sp_rename上的文檔http://msdn.microsoft.com/en-us/library/ms188351.aspx – IDisposable 2011-02-03 22:32:44
@Mitch小麥的解決方案效果很好。但是,偶爾會出現「無效的列名稱:newColumn」錯誤,因爲在嘗試運行更新之前表尚未更新。
爲了解決這個問題,添加GO語句將二者分開成批次:
-- Create a new Column (unpersisted):
ALTER TABLE MyTable
ADD newColumn DatatypeOfPersistedColumn
GO
UPDATE myTable
SET newColumn = PersistedColumn
-- Delete the persisted column
ALTER TABLE MyTable
DROP COLUMN PersistedColumn
-- Rename new column to old name
EXEC sp_rename 'MyTable.newColumn', 'PersistedColumn', 'COLUMN'
我想說的是前者。 – leppie 2010-11-10 11:18:03
將持久列實現爲「真實」列的優點是什麼? Mitch Wheat的 – 2010-11-10 11:23:54
:這是遺留數據庫的遷移任務。 – 2010-11-10 12:59:48