Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/sql-server/21.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Sql server 将计算列转换为正则列_Sql Server_Database_Schema_Calculated Columns - Fatal编程技术网

Sql server 将计算列转换为正则列

Sql server 将计算列转换为正则列,sql-server,database,schema,calculated-columns,Sql Server,Database,Schema,Calculated Columns,我在SQLServer2005中的一个大表中有一个持久化的计算列 我想将其转换为常规列,保留当前值 我是否必须在事务中重新创建列并更新整个表, 或者,是否可以只更改计算列规格,以及如何更改?只需在SSMS表格的设计模式下从“计算列规格”中删除公式即可。值将按原样保留在列中。假设将计算列转换为“实”列的原因是您希望保留现有值/功能,但在需要时添加覆盖它的功能,您可以添加一个新列(仅在覆盖现有派生值时填充),并将计算列的定义更改为COALESCE(NewColumn,旧的计算定义)@Mitch-Wh

我在SQLServer2005中的一个大表中有一个持久化的计算列

我想将其转换为常规列,保留当前值

我是否必须在事务中重新创建列并更新整个表,
或者,是否可以只更改计算列规格,以及如何更改?

只需在SSMS表格的设计模式下从“计算列规格”中删除公式即可。值将按原样保留在列中。

假设将计算列转换为“实”列的原因是您希望保留现有值/功能,但在需要时添加覆盖它的功能,您可以添加一个新列(仅在覆盖现有派生值时填充),并将计算列的定义更改为
COALESCE(NewColumn,
旧的计算定义

@Mitch-Wheat的解决方案非常有效。但是,有时这会引发“无效列名:newColumn”错误,因为表在尝试运行更新之前尚未更新

-- 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
要解决此问题,请添加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'

这样,ManagementStudio实际上会重新创建表,并重新插入值。这是一个生产中的大型数据库,因此它对我不起作用。这是否意味着新数据库不支持计算列?我需要保留列的名称。然后使用EXEC sp_rename'newColumn',PersistedColumn',column'删除PersistedColumn后进行重命名
-- 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'