May be indexed when SQL Server requirements are met
Automatically updates when source values change
When to Use PERSISTED
[A persisted computed column may be useful when:]
The expression is used frequently.
The calculation is expensive.
The column is used for searching or sorting.
The column needs an index.
The stored value improves query performance.
For example, a search procedure may repeatedly use: WHERE SearchColumn LIKE '%' + @SearchText + '%'
Copy
Search Site
Search Google
Persisting
Copy
Search Site
Search Google
the value may avoid recalculating a complicated expression during every search. However, performance should be tested. Persisting every computed column is not automatically better because it increases storage and adds work during inserts and updates.
[Non-Persisted Computed Column]When to Use a Non-Persisted Column A non-persisted computed column may be better when:
The expression is simple.
The column is not queried frequently.
Storage usage is more important than calculation cost.
The source columns rarely appear in search conditions.
The computed value does not require an index.
A simple concatenation may not require persistence unless it is heavily used.
[SQK Server - ALTER TABLE statement]Generate the ALTER TABLE Script Automatically The following query generates the appropriate ALTER TABLE statement using the existing computed-column definition:
SELECT'ALTER TABLE '
+ QUOTENAME(SCHEMA_NAME(t.schema_id))
+ '.'
+ QUOTENAME(t.name)
+ ' ADD '
+ QUOTENAME(c.name)
+ ' AS '
+ cc.definition
+ CASE
WHEN cc.is_persisted = 1 THEN ' PERSISTED;'
ELSE ';'
END AS AddComputedColumnScript
FROMsys.computed_columnsAS cc
INNERJOINsys.columnsAS c
ON cc.object_id = c.object_idANDcc.column_id = c.column_idINNERJOINsys.tablesAS t
ON cc.object_id = t.object_idWHEREc.name = 'SearchColumn';
[SQK Server - Generate Code]Run this query in the database that already contains the computed column. It will generate a statement similar to:
SELECTTOP20
ProductName,
CategoryName,
SearchColumn
FROMdbo.Products;
Important Migration Considerations
Before copying a computed column to another database, verify:
The destination table exists.
The destination table has the required source columns.
The source column data types are compatible.
Any functions used by the expression also exist.
The computed column does not already exist.
The persisted setting matches the original database.
Any related indexes are scripted separately.
Adding the computed column does not automatically recreate an index associated with it. Indexes, constraints, and dependent stored procedures should also be compared between the databases.
Computed columns are useful for creating reusable search values without requiring applications to manually maintain duplicate data. By retrieving the original expression from sys.computed_columns
Copy
Search Site
Search Google
, you can accurately recreate the column and preserve whether SQL Server stores the result using PERSISTED