Search code examples
sql-servert-sqlsql-execution-plantable-valued-parameterscross-apply

Wrapper TSQL Table-valued Function is slow


I built a wrapper function that currently just calls another table-valued Function but it just added a huge amount to the execution time as Client processing time. Is there a faster way to do this?

Without wrapper: enter image description here

With Wrapper: enter image description here

Wrapper function:

CREATE FUNCTION [console].[getCalculosRequisita]
(   

    @Disponivel BIGINT,
    @mediaDiaria float,
    @DiasStockArtigo INT, 
    @DiasAntes INT, 
    @SaidasPorMes float, 
    @QtdEncomendada2Meses BIGINT,
    @StockAtual BIGINT,
    @QtdRequisitada BIGINT,
    @caixaMinima INT

)
RETURNS @tbl TABLE 
(
    DiasAteRotura INT,
    AcaoRequisita varchar(10),
    Aconselhada BIGINT
)
AS
BEGIN

--future configuration check
--future log input

INSERT INTO @tbl SELECT DiasAteRotura, AcaoRequisita,Aconselhada
FROM [cartridge].[getCalculosRequisitaTSQL]
(
    @Disponivel ,
    @mediaDiaria ,
    @DiasStockArtigo , 
    @DiasAntes , 
    @SaidasPorMes , 
    @QtdEncomendada2Meses ,
    @StockAtual ,
    @QtdRequisitada ,
    @caixaMinima
)


--future log output

RETURN
END

GO

Solution

  • Do it as an inline TVF, which is much, much faster:

    CREATE FUNCTION [console].[getCalculosRequisita]
    (   
    
        @Disponivel BIGINT,
        @mediaDiaria float,
        @DiasStockArtigo INT, 
        @DiasAntes INT, 
        @SaidasPorMes float, 
        @QtdEncomendada2Meses BIGINT,
        @StockAtual BIGINT,
        @QtdRequisitada BIGINT,
        @caixaMinima INT
    )
    RETURNS TABLE -- WITH SCHEMABINDING  -- preferable, but then you can't change the underlying function
    (
        DiasAteRotura INT,
        AcaoRequisita varchar(10),
        Aconselhada BIGINT
    )
    AS RETURN
    (SELECT DiasAteRotura, AcaoRequisita, Aconselhada
    FROM [cartridge].[getCalculosRequisitaTSQL]
    (
        @Disponivel ,
        @mediaDiaria ,
        @DiasStockArtigo , 
        @DiasAntes , 
        @SaidasPorMes , 
        @QtdEncomendada2Meses ,
        @StockAtual ,
        @QtdRequisitada ,
        @caixaMinima
    ) AS t
    );
    GO
    

    Obviously, if you do this then you cannot do any other inserts. In any case logging would be impossible, so I'm not sure what you were planning on doing.

    You have not given the code for the underlying function. Perhaps that can be done as an iTVF also.