Untitled
unknown
sql
2 years ago
1.2 kB
4
Indexable
Never
ALTER FUNCTION [dbo].[Fn_GetConnections] ( @client_id INT ) RETURNS @Res TABLE ( CLIENT_ID INT ) AS BEGIN INSERT INTO @Res SELECT @client_id INSERT INTO @Res SELECT REL_CLIENT_NO FROM dbo.CLI_REL WHERE CLIENT_NO = @client_id DECLARE @Id INT DECLARE searchConnections CURSOR LOCAL STATIC READ_ONLY FORWARD_ONLY FOR SELECT REL_CLIENT_NO FROM dbo.CLI_REL WHERE CLIENT_NO = @client_id OPEN searchConnections IF @@CURSOR_ROWS > 0 BEGIN FETCH NEXT FROM searchConnections INTO @Id WHILE @@FETCH_STATUS = 0 BEGIN IF EXISTS(SELECT 1 FROM dbo.CLI_REL WHERE CLIENT_NO = @Id ) BEGIN INSERT INTO @Res SELECT DISTINCT C.CLIENT_ID from [Fn_GetConnections](@Id) C INNER JOIN @Res R ON C.CLIENT_ID != R.CLIENT_ID AND C.CLIENT_ID<>@client_id WHERE NOT EXISTS (SELECT 1 FROM @Res r WHERE r.CLIENT_ID=C.CLIENT_ID) END FETCH NEXT FROM searchConnections INTO @Id END ;WITH CTE AS (SELECT *,ROW_NUMBER() OVER (PARTITION BY CLIENT_ID ORDER BY CLIENT_ID) AS RN FROM @Res) DELETE FROM CTE WHERE RN<>1 END CLOSE searchConnections DEALLOCATE searchConnections RETURN END