Skip to content

Instantly share code, notes, and snippets.

@spaghettidba
Last active August 29, 2015 14:22
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save spaghettidba/142453fd3ff0519a0ba1 to your computer and use it in GitHub Desktop.
Save spaghettidba/142453fd3ff0519a0ba1 to your computer and use it in GitHub Desktop.
ALTER function [dbo].[FN_ObtenerArbolEmpresa](@empresaID int)
RETURNS TABLE
AS
RETURN
WITH temp
AS (
-- anchor
SELECT id_empresa_hijo, id_empresa_padre
FROM empresa_x_empresa with(nolock)
WHERE id_empresa_padre = @empresaID
UNION ALL
--recursive member
SELECT t.id_empresa_hijo, t.id_empresa_padre
FROM empresa_x_empresa AS t with(nolock)
JOIN temp AS a
ON t.id_empresa_padre = a.id_empresa_hijo
)
SELECT id_empresa_hijo
FROM (
select id_empresa_hijo
from empresa_x_empresa with (nolock)
UNION ALL
select 0
) AS isZero
WHERE @empresaID = 0
UNION ALL
SELECT id_empresa_hijo
FROM (
SELECT id_empresa_hijo
FROM temp
UNION ALL
select @empresaID
) AS notZero
WHERE @empresaID <> 0
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment