Computed Column cannot be Persisted

前端 未结 4 1307
自闭症患者
自闭症患者 2020-12-29 21:46

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

相关标签:
4条回答
  • 2020-12-29 22:24

    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,
    
    0 讨论(0)
  • 2020-12-29 22:37

    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
    
    0 讨论(0)
  • 2020-12-29 22:42

    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 讨论(0)
  • 2020-12-29 22:43

    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.

    0 讨论(0)
提交回复
热议问题