Saturday, April 5, 2014

Error: Computed column 'X' in table 'Y' cannot be persisted because the column is non-deterministic.

This error could appear when you try to add a persisted computed column to a table, for example:


or
Percentage AS [dbo].[fn_getPercentage](Total) PERSISTED

you may get an error like:
Computed column 'Actor' in table 'Tmp_OrgData' cannot be persisted because the column is non-deterministic.

The reason is that the function that fills this column is not flagged to be deterministic (a deterministic function is the function that returns the same value every time it is executed with the same parameters values; so GETDATE() is non-deterministic function because it returns different value (date/time) every time we run it). And to mark a function as deterministic you have to add WITH SCHEMABINDING between RETURNS... and AS BEGIN... in the function definition. For example:

CREATE FUNCTION fn_getPercentage( @Total INT)
    RETURNS INT
WITH SCHEMABINDING  
AS
BEGIN
    RETURN SELECT @Total/countOfSomething FROM tblOrgData
END

Note: you cannot make a persisted column out of a recursive function.

No comments:

Post a Comment