This function is a bit of a bottleneck but is only a small part of a larger query. Are there any changes that can be made to get it to perform better? The UNION is unavoidable, but is the WITH clause the only way? (this is not my original code, I can do pretty basic CRUD operations and am trying to improve performance)
USE [DB]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER FUNCTION [dbo].[ufnWidgetWithChildren] (@RootWidget INT)
RETURNS @WidgetList TABLE (
WidgetID INT
,WidgetName VARCHAR(50)
,ParentWidgetID INT
)
AS
BEGIN
WITH [CTE]
AS (
SELECT WidgetID
,WidgetName
,ParentWidgetID
FROM Widgets c
WHERE c.WidgetID = @RootWidget
UNION ALL
SELECT c.WidgetID
,c.WidgetName
,c.ParentWidgetID
FROM [CTE] p
,Widgets c
WHERE c.[ParentWidgetID] = p.[WidgetID]
)
INSERT INTO @WidgetList
SELECT WidgetID
,WidgetName
,ParentWidgetID
FROM [CTE]
ORDER BY WidgetID
RETURN
END