开发者

Computed Column cannot be Persisted

开发者 https://www.devze.com 2022-12-11 15:10 出处:网络
I have a custom function, and I am trying to created a persisted column using this function. It is giving me following error.

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.

开发者_如何学C

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.


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


Instead of calling the UDF, Set the computed column expression to

Case When Len(EmployeeSSN) = 0 Then 
      SUBSTRING(EmployeeSSN, 1, 3) + '-' + 
      SUBSTRING(EmployeeSSN, 4, 2) + '-' + 
      SUBSTRING(EmployeeSSN, 6, 4)
    Else EmployeeSSN End

In the Create Table script you can add a column:

[NewColumnName]  As
   (Case When len([UpdateUserId])=(0) T
         Then (((substring([UpdateUserId],(1),(3))+'-')+
                 substring([UpdateUserId],(4),(2)))+'-')+
                 substring([UpdateUserId],(6),(4)) 
         Else [UpdateUserId] End) PERSISTED,


Create a non-computed column of appropriate datatype. Create an Insert trigger (and an Update trigger if data will change). You can then persist the function output in a column.

ALTER TABLE SomeTable ADD FormattedSSN VARCHAR(11)
GO

CREATE TRIGGER dbo.TR_I_SomeTable ON  dbo.SomeTable AFTER INSERT
AS 
BEGIN
    SET NOCOUNT ON;

    update s
    set s.FormattedSSN = dbo.FormatSSN()
    from SomeTable AS s
        join inserted i on i.id = s.id

END
GO
0

精彩评论

暂无评论...
验证码 换一张
取 消