Query to alter the Computed Column

  • Tim,

    I read your article “The Mighty, Mighty Computed Column” and it helped me a lot to understand the concept of computed column. I have a query. I have a computed column in my table and what I want is to alter this column and its computed criteria. Please check the example for more info:

    Create table Dummy

    (

    ADecimal (12, 0),

    BDecimal (12, 0),

    CDecimal (12, 0),

    DAs (A + B - C) –Computed column

    )

    I want to change D as

    D(Case When B = 0 Then 0 Else (A + B - C) End)

    How can I do that? Please help

  • From BOL (bolding mine):

    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. For more information, see sp_dbcmptlevel (Transact-SQL).

    The modified column cannot be any one of the following:

    * A column with a timestamp data type.

    * The ROWGUIDCOL for the table.

    * A computed column or used in a computed column.

    * Used in an index, unless the column is a varchar, nvarchar, or varbinary data type, the data type is not changed, the new size is equal to or larger than the old size, and the index is not the result of a PRIMARY KEY constraint.

    * Used in statistics generated by the CREATE STATISTICS statement unless the column is a varchar, nvarchar, or varbinary data type, the data type is not changed, and the new size is equal to or greater than the old size, or if the column is changed from not null to null. First, remove the statistics using the DROP STATISTICS statement. Statistics that are automatically generated by the query optimizer are automatically dropped by ALTER COLUMN.

    * Used in a PRIMARY KEY or [FOREIGN KEY] REFERENCES constraint.

    * Used in a CHECK or UNIQUE constraint. However, changing the length of a variable-length column used in a CHECK or UNIQUE constraint is allowed.

    * Associated with a default definition. However, the length, precision, or scale of a column can be changed if the data type is not changed.

    The data type of text, ntext and image columns can be changed only in the following ways:

    o text to varchar(max), nvarchar(max), or xml

    o ntext to varchar(max), nvarchar(max), or xml

    o image to varbinary(max)

    So you would need to Drop the computed column and re-add it.

    ALTER TABLE [Dummy] DROP COLUMN D

    GO

    ALTER TABLE DUMMY ADD D AS (CASE WHEN B = 0 THEN 0 ELSE A+B-C End)

Viewing 2 posts - 1 through 1 (of 1 total)

You must be logged in to reply to this topic. Login to reply