I have the following recursive function which outputs a delimited list of ids. ALTER FUNCTION [dbo].[fn_GetLeads] ( @id int) RETURNS varchar(MAX) ASBEGINDECLARE @rowID int, @tmp varchar(MAX), @ret varchar(MAX), @leadID intSELECT @ret = ''SELECT @rowID = MIN(ID) FROM [Delegates] WHERE DelegateID = @id WHILE @rowID IS NOT NULL BEGIN SET @leadID = (SELECT LeadID FROM [Delegates] WHERE ID = @rowID) SELECT @ret = CAST(@leadID AS varchar(12)) + ' ' + @ret EXEC @tmp = dbo.fn_GetLeads @leadID SELECT @ret = CAST(@tmp AS varchar(MAX)) + @ret SELECT @rowID = MIN(ID) FROM [Delegates] WHERE DelegateID = @id AND ID > @rowID ENDRETURN @retEND
I'm encountering the issue where if a delegate is the lead of a pre-existing delegate the function is caught in an endless loop. I need assistance with creating a method to check if the delegate id already exists within the list and if so, it is skipped/ignored.My delegate table:CREATE TABLE [dbo].[Delegates]( [ID] [int] IDENTITY(1,1) NOT NULL, [LeadID] [int] NULL, [DelegateID] [int] NULL,)Any assistance is appreciated.Best,Fezzik