Я пытаюсь изменить табличную функцию для повышения производительности хранимой процедуры, но не могу получить тот же результат. Можете ли вы сказать мне, где я иду не так?
Оригинал:
create FUNCTION [dbo].[fun_eess1] (
@institucion int ,
@disa int,
@red int,
@mred int) RETURNS @tbl TABLE (idlista [int] IDENTITY, institucion [int], disa [int], red [int], mred [int], establecimiento varchar(10)) AS BEGIN
IF (@institucion=1) -- First Condition */ where @institucion=1 then UNION ALL
BEGIN
INSERT INTO @tbl ([institucion], [disa], [red], [mred], [establecimiento])
SELECT DISTINCT [c_institucion], [c_disa], [c_red], [c_microred], [codrenae] FROM [dbo].[RENAE]
WHERE
[c_institucion]=@institucion AND [c_disa]=(CASE @disa WHEN -1 THEN [c_disa] ELSE @disa END)
AND [c_red]=(CASE @red WHEN -1 THEN [c_red] ELSE @red END)
AND [c_microred]=(CASE @mred WHEN -1 THEN [c_microred] ELSE @mred END)
END ELSE
BEGIN
IF (@institucion=15) -- Second Condition */ where @institucion=15 then UNION ALL
BEGIN
INSERT INTO @tbl ([institucion], [disa], [red], [mred], [establecimiento])
SELECT DISTINCT [c_institucion], [c_disa], [c_red], [c_microred], [codrenae] FROM [dbo].[RENAE]
WHERE [c_institucion]='1' AND [c_disa]=(CASE @disa WHEN -1 THEN [c_disa] ELSE @disa END)
AND [c_red]=(CASE @red WHEN -1 THEN [c_red] ELSE @red END)
AND [c_microred]=(CASE @mred WHEN -1 THEN [c_microred] ELSE @mred END)
INSERT INTO @tbl ([institucion], [disa], [red], [mred], [establecimiento])
SELECT [org].[CodigoOrganizacion], [di].[iddisa], [r].[idred], [mi].[idmred], CAST ([es].[idestablecimiento] AS varchar) FROM [dbo].[Establecimientos] es
INNER JOIN [dbo].[microred] mi ON [mi].[idmred]=[es].[microred]
INNER JOIN [dbo].[Red] r ON [mi].[red] = [r].[idred]
INNER JOIN [dbo].[Disa] di ON [r].[disa] = [di].[iddisa]
INNER JOIN [dbo].[Organizacion] org ON [di].[institucion] = [org].[CodigoOrganizacion]
WHERE [org].[CodigoOrganizacion] in ('2','3','4','5','6','13') AND [di].[iddisa]=(case @disa when -1 then [iddisa] else @disa end) AND [r].[idred]=(case @red when -1 then [idred] else @red end) AND [mi].[idmred]=(case @mred when -1 then [idmred] else @mred end)
END
ELSE
BEGIN -- Third Condition? */ where @institucion is not (1,15) then UNION ALL
INSERT INTO @tbl ([institucion], [disa], [red], [mred], [establecimiento])
SELECT [org].[CodigoOrganizacion], [di].[iddisa], [r].[idred], [mi].[idmred], CAST ([es].[idestablecimiento] AS varchar) FROM [dbo].[Establecimientos] es
INNER JOIN [dbo].[microred] mi ON [mi].[idmred]=[es].[microred]
INNER JOIN [dbo].[Red] r ON [mi].[red] = [r].[idred]
INNER JOIN [dbo].[Disa] di ON [r].[disa] = [di].[iddisa]
INNER JOIN [dbo].[Organizacion] org ON [di].[institucion] = [org].[CodigoOrganizacion]
WHERE [org].[CodigoOrganizacion]=@institucion AND [di].[iddisa]=(case @disa when -1 then [iddisa] else @disa end) AND [r].[idred]=(case @red when -1 then [idred] else @red end) AND [mi].[idmred]=(case @mred when -1 then [idmred] else @mred end)
END END
Надеюсь, кто-нибудь может мне помочь!