Monday, March 19, 2012

calling a udf from a computed field

I am trying desparately to build a user defined function on the Microsoft SQL Server 2000 viewer and when it is performed I get the following message:

[Microsoft][ODB SQL Server Driver][SQL Server] Maximum stored procedure, function, trigger, or view nesting level exceeded

Is there any problem using sql MAX() built in function? How can I resolve this issue?

The UDF code is:
CREATE FUNCTION TestFunc (@.Syn int)
RETURNS int AS
BEGIN
IF @.Syn IS NULL
RETURN 1
DECLARE @.NewPersonID INT
SELECT @.NewPersonID = MAX(PersonID)
FROM GO_Test
WHERE SynagogueID = @.Syn
RETURN ISNULL(@.NewPersonID + 1, 1)
END

I call the function from the 'Formula' propery of a computed field of a table like this:
([dbo].[TestFunc]([SynagogueID]))

while SynagogueID is a field on the same table.


The error message indicates that you have reached the maximum nesting level which is 32. But your code doesn't seem to indicate that this error is due to the UDF logic. What operation are you performing when you get the error? You need to trace the SQL statements and find the exact one that is causing the error. Look for nested triggers, UDFs with recursion etc.

Lastly, you should avoid using scalar UDFs especially those that perform data access in computed columns. The performance of queries referencing the computed column will suffer badly. Instead, you can define a view with a sub-select that does the same thing but much more efficiently. Ex:

select ..., coalesce((select max(g.PersonID) from GO_Test AS g where g.SynagogueID = t.SynagogueID), 0) + 1 as PerId

from tbl as t

No comments:

Post a Comment