Link to home
Start Free TrialLog in
Avatar of pureauto
pureautoFlag for United States of America

asked on

SQL: How do I enable optional parameters on a recursive table valued funtion?

I have a recursive table valued function in SQL Server 2005 that currently works great.  Now I want to make the parameter optional.  If @ID is null I want to assign it a value from a select statement.  I have tried to insert the following if statement into the body of the function many different ways and I get always get multiple errors:

IF (@ID IS NULL) SET @ID = (SELECT TOP 1 ItemCode FROM ConfigDropDownLists WHERE ParentID IS NULL AND isMapAggPnt = 'true')

What is the proper way to do this?
ALTER FUNCTION [dbo].[GetAggPointAndChildCoordinates]
(
	@ID VARCHAR(50)
)
RETURNS TABLE
AS
RETURN
(
	WITH Results AS
	(
	-- Anchor member definition
		SELECT cdl.ParentID AS ParentID, cdl.ItemCode AS ID, cdl.ListName AS [Type], cdl.ItemName AS [Name], cdl.Polygon, 1 AS [Level]
		FROM ConfigDropdownLists AS cdl
		WHERE cdl.ParentID = @ID AND cdl.IsMapAggPnt = 'True'
		UNION ALL
	-- Recursive member definition
		SELECT cdl.ParentID AS ParentID, cdl.ItemCode AS ID, cdl.ListName AS [Type], cdl.ItemName AS [Name], cdl.Polygon, [Level] + 1
		FROM ConfigDropdownLists AS cdl
		INNER JOIN Results AS r
			ON cdl.ParentID = r.ID
	)
 
	-- Statement that executes the CTE
	SELECT ParentID AS [ParentID], ItemCode AS ID, ListName AS [Type], ItemName AS [Name], 0 AS [Level],isnull(Polygon, dbo.GetAggregationPointPerimeterCSV(ItemCode)) AS Coordinates FROM ConfigDropdownLists WHERE ItemCode = @ID
	UNION ALL 
	SELECT ParentID, ID, [Type], [Name], [Level],isnull(Polygon, dbo.GetAggregationPointPerimeterCSV(ID)) AS Coordinates
	FROM Results
)

Open in new window

ASKER CERTIFIED SOLUTION
Avatar of reb73
reb73
Flag of Ireland image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of pureauto

ASKER

Thanks reb, that worked well.  I had experimented with the multistatement table valued functions, but apparently my syntax was off.
thanks again.