简体   繁体   English

SQL - 如何在计算列上更改COLUMN

[英]SQL - How to ALTER COLUMN on a computed column

I'm working with SQL Server 2008. Is it possible to alter a computed column without actually dropping the column and then adding it again (which I can get to work)? 我正在使用SQL Server 2008.是否可以更改计算列而不实际删除列然后再次添加它(我可以开始工作)? For example, I have this table: 例如,我有这个表:

CREATE TABLE [dbo].[Prices](
[Price] [numeric](8,3) NOT NULL,
[AdjPrice] AS [Price] / [AdjFactor],
[AdjFactor] [numeric](8,3) NOT NULL)

Later realizing that I have a potential divide by zero error I want to alter the [Adjprice] column to handle this, but if I just drop the column and add it again, I lose the column order. 后来意识到我有一个可能除以零的错误我想改变[Adjprice]列来处理这个,但是如果我只是删除列并再次添加它,我就失去了列顺序。

I want to do something like: 我想做的事情如下:

ALTER TABLE dbo.[Prices]
ALTER COLUMN [AdjPrice] AS (CASE WHEN [AdjFactor] = 0 THEN 0 ELSE [Price] / [AdjFactor] END)

But this isn't correct. 但这不正确。 If this is possible, or there is another solution, I would appreciate the help. 如果这是可能的,或者有另一种解决方案,我将不胜感激。

Unfortunately, you cannot do this without dropping the column first. 不幸的是,如果不先删除列,就不能这样做。

From MSDN : 来自MSDN

ALTER COLUMN ALTER COLUMN
Specifies that the named column is to be changed or altered. 指定要更改或更改命名列。 ALTER COLUMN is not allowed if the compatibility level is 65 or lower. 如果兼容级别为65或更低,则不允许使用ALTER COLUMN。 For more information, see sp_dbcmptlevel (Transact-SQL). 有关更多信息,请参见sp_dbcmptlevel(Transact-SQL)。

  • The modified column cannot be any one of the following: 修改后的列不能是以下任何一种:

    • A computed column or used in a computed column. 计算列或在计算列中使用。

if you must maintain order, copy the data into a duplicate table, then rebuild the table to keep your column order, then copy the data from the duplicate table back in. 如果必须维护订单,请将数据复制到重复的表中,然后重建表以保持列顺序,然后将数据从重复表中复制回来。

Just be sure to do this when there is no activity going on. 当没有活动时,请确保这样做。

NO 没有

if it is computed, what is the big deal dropping it and adding it again? 如果计算好了,丢掉它并重新添加它有什么大不了的? is it PERSISTED and there are million of rows? 它是PERSISTED并且有数百万行?

I do not think you can alter this column with out dropping. 我不认为你可以改变这个专栏而不用掉线。 So drop the colum then add new column. 因此,删除列,然后添加新列。

If you find out any other way to do this please tell me. 如果您发现任何其他方法,请告诉我。

its easy to overcome divide by zero error 它容易克服零误差

use 采用

SELECT
( 100 / NULLIF( 0, 0 ) ) AS value

it will return a null, if 0 is in that column, 如果该列中有0,它将返回null,

instead of alter go for update by using the above example 而不是使用上面的例子来改变更新

Also read the 3rd normalization for computed column 还要读取计算列的第3个标准化

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM