Search code examples
sqlsql-serversql-server-2008calculated-columnsalter

Alter a column to be calculated SQL SERVER


I have a table similar to this one:

CREATE TABLE [dbo].[test](
    [id] [int] IDENTITY(1,1) NOT NULL,
    [action] [varchar](50),
    [id_source] [int] NULL,
    [id_dest] [int] NULL,
    [name] [varchar](255)
)

I am trying to convert the name column to be calculated. I tried something similar to this with no success

ALTER TABLE [dbo].[test] 
ALTER COLUMN [name] AS ([dbo].[f_get_name]([id_source],[id_dest],[action]))

The table at the moment is empty. Is it possible to achieve this with an ALTER command? Thanks


Solution

  • You can't alter it.

    ALTER COLUMN

    Specifies that the named column is to be changed or altered.

    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.

    You need to drop and recreate:

    ALTER TABLE [dbo].[test]
    DROP COLUMN [name];
    
    ALTER TABLE [dbo].[test]
    ADD [name] AS ([dbo].[f_get_name]([id_source],[id_dest],[action]));