I have a table with a calculated field (Test
) based on the result of a function (MyFunctionTest
) and i want make it PERSISTED
and add an index for performance improvments, eg.:
CREATE TABLE [dbo].[TestTable] (
[Id] [int] IDENTITY(1,1) NOT NULL,
[Foo] [int] NOT NULL,
[Test] AS ([dbo].[MyFunctionTest]([Foo])) PERSISTED,
CONSTRAINT [PK_TestTable] PRIMARY KEY CLUSTERED
(
[Id] ASC
) WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]
MyFunctionTest
is:
ALTER FUNCTION [dbo].[MyFunctionTest]
(
@foo int
)
RETURNS int
AS
BEGIN
RETURN @foo * 2
END
But, sql server 2005 on save show the error
Computed column 'Test' in table 'Tmp_TestTable' cannot be persisted because the column is non-deterministic.
why MyFunctionTest
isn't deterministic?
SOLUTION
Add WITH SCHEMABINDING to the function make it deterministic
ALTER FUNCTION [dbo].[MyFunctionTest]
(
@foo int
)
RETURNS int
WITH SCHEMABINDING
AS
BEGIN
RETURN @foo * 2
END