This is something I’ve been doing a lot lately.
Seem to find myself googling for the syntax every time I have to so this is a reference for me, mostly, but you can use it if you behave.
The T-SQL syntax for adding a calculated column to a table looks like this:
ALTER TABLE [<TableName>] ADD <NewCalculatedColumnName> AS (<SQL for value>) PERSISTED
A couple of notes:
- <TableName> is the name of the table you’re adding a column to.
- <NewCalculatedColumnName> is the name of the new column
- <SQL for value> is a valid T-SQL statement.
- PERSISTED – Specifies that the Database Engine will physically store the computed values in the table, and update the values when any other columns on which the computed column depends are updated.