Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Computed Column cannot be Persisted

Tags:

sql

sql-server

I have a custom function, and I am trying to created a persisted column using this function.

It is giving me following error.

Computed column 'FormattedSSN' in table 'SomeTable' cannot be persisted because the column is non-deterministic.

Here is the function:

ALTER FUNCTION [dbo].[FormatSSN]() RETURNS VARCHAR(11) AS BEGIN     return ''; END 

Here is the query to add the column using the function:

ALTER TABLE SomeTable ADD FormattedSSN as dbo.FormatSSN() PERSISTED 

Please suggest if there is any way out. Thanks.

like image 360
noob.spt Avatar asked Nov 13 '09 21:11

noob.spt


People also ask

Is persisted in SQL computed column?

Computed columns can be persisted. It means that SQL Server physically stores the data of the computed columns on disk. When you change data in the table, SQL Server computes the result based on the expression of the computed columns and stores the results in these persisted columns physically.

How do you check if computed column is persisted?

A persisted computed column is one that is physically stored in the table. If you don't specify that it's persisted, then the column's value will be calculated each time you run a query against it. You can query the sys. computed_columns system catalog view to find out whether a computed column is marked as persisted.

Are there any disadvantages of using computed column?

Some Limitations. You can not reference columns from other tables for a computed column expression directly. You can not apply insert or update statements on computed columns.

What is a computed column?

A computed column is a virtual column that is not physically stored in the table, unless the column is marked PERSISTED. A computed column expression can use data from other columns to calculate a value for the column to which it belongs.


2 Answers

Add WITH SCHEMABINDING to the function like this:

ALTER FUNCTION [dbo].[FormatSSN] ( @SSN    VARCHAR(9) ) RETURNS CHAR(11) WITH SCHEMABINDING AS BEGIN   your stuff here END 

and then run this to verify:

IF OBJECTPROPERTY (OBJECT_ID(N'[dbo].[FormatSSN]'),'IsDeterministic') = 1    PRINT 'Function is detrministic.' ELSE IF OBJECTPROPERTY (OBJECT_ID(N'[dbo].[FormatSSN]'),'IsDeterministic') = 0    PRINT 'Function is NOT detrministic' GO 

Works here.

like image 58
Damir Sudarevic Avatar answered Sep 24 '22 07:09

Damir Sudarevic


How about specifying the definition directly:

ALTER TABLE SomeTable ADD FormattedSSN as     case when len(EmployeeSSN) = 9 then             substring(EmployeeSSN, 1, 3) + '-' +             substring(EmployeeSSN, 4, 2) + '-' +             substring(EmployeeSSN, 6, 4)     else EmployeeSSN end PERSISTED 
like image 23
schinazi Avatar answered Sep 23 '22 07:09

schinazi