简体   繁体   中英

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

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]));

Is it possible to achieve this with an ALTER command?

No there is no way to achieve it by altering the table. The ALTER table command will restrict you to do so since your column involves computation.

Solution:

You need to drop the column and recreate it again like this:

alter table [dbo].[test] 
drop column [name];

alter table [dbo].[test] 
add [name] as ([dbo].[f_get_name]([id_source],[id_dest],[action]));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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