How do you add a computed column to a Table?

86,143

The syntax I was looking for is:

alter table TABLE_NAME
add [column_name] as (**COLUMN-SQL**)
Share:
86,143
Chris Pfohl
Author by

Chris Pfohl

Full-stack, stack-agnostic, problem solver. I love data, great developer experience, keeping the big picture in mind and developing people-proof systems (mostly me-proof, if I'm being honest).

Updated on July 05, 2022

Comments

  • Chris Pfohl
    Chris Pfohl about 2 years

    How can I add a computed column to a table that already exists? S.O. has Computed Column Help - TSQL but no information about adding them.

  • David Knight
    David Knight over 10 years
    alter table TABLE_NAME add [column_name] as (**COLUMN-SQL**)
  • veeresh yh
    veeresh yh over 8 years
    EX: alter table TABLE_NAME add [double_count] as (count * 2)
  • Sal
    Sal almost 8 years
    To create a persisted column (calculated when the data is inserted) you can add the Persisted keyword: alter table TABLE_NAME add [column_name] as (COLUMN-SQL) PERSISTED
  • enigma6205
    enigma6205 over 5 years
    THis does now work when adding Row_Number column. ALTER TABLE MYDB.[dbo].[Table1] ADD Rn INT NOT NULL AS (ROW_NUMBER() OVER (PARTITION BY [MyColumn] ORDER BY [MyColumn]));
  • Chris Pfohl
    Chris Pfohl over 5 years
    I imagine that's a result of using a windowing function in a calculated column.