Search code examples
sqlsql-serverfunctionsql-server-2016

Computed column in SQL


I need to create a computed column for an existing column in a table.

ALTER TABLE MyTable 
    ALTER COLUMN MyComputedColumn INT GENERATED ALWAYS AS DATEDIFF(DD, GETDATE(), MyDateColumn)

It's throwing an error in the DATEDIFF function, doesn't like the DD parameter and throws error on GETDATE() too.

Any idea/suggestion will help. Thank you.


Solution

  • To change a calculated column, you must first DROP column and then redefine the column as calculated.

    ALTER TABLE MyTable DROP COLUMN MyComputedColumn 
    ALTER TABLE MyTable ADD MyComputedColumn AS DATEDIFF(DD, GETDATE(), MyDateColumn)