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.
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.
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.
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.
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With