• No less than four levels of nested queries! Good Lord, no wonder it takes so long. Examining the code, none of it, even the few queries, look as if they've been written by an experienced SQL developer and there are mistakes - compare these two cursor definitions:

    -- CUR_WAREHOUSE

    SELECT WHSCODE -- @WAREHOUSE

    FROM OWHS

    WHERE ((WHSCODE >= @F_WAREHOUSE AND WHSCODE <= @T_WAREHOUSE)

    OR (@F_WAREHOUSE = '' AND @T_WAREHOUSE = ''))

    ORDER BY WHSCODE

    -- CUR_ITEMGROUP

    SELECT ITMSGRPCOD -- @ITEMGROUP

    FROM OITB

    WHERE ((ITMSGRPCOD = @F_ITEMGROUP AND ITMSGRPCOD <= @T_ITEMGROUP)

    OR (@F_ITEMGROUP = ''AND @T_ITEMGROUP = ''))

    ORDER BY ITMSGRPCOD

    The second definition is supposed to have a range in the WHERE clause.

    I'd suggest that if this function generates correct results, then it's by accident, not by design. However, it shouldn't be too tough to convert it to a proper set-based function. The four nested cursors can be combined something like this:

    SELECT w.WHSCODE, T6.ITEMCODE, T0.ItmsGrpCod,

    (CONVERT(NUMERIC(16,4), T6.INQTY)), -- @INQTY

    (CONVERT(NUMERIC(16,4), T6.OUTQTY)), -- @OUTQTY

    (CONVERT(NUMERIC(16,4), T6.TRANSVALUE)), -- @CALCPRICE

    T6.TRANSTYPE -- @TRANSTYPE

    FROM OINM T6

    INNER JOIN OWHS w

    ON w.WHSCODE = T6.WAREHOUSE

    INNER JOIN OITM T0

    ON T0.[ItemCode] = T6.ITEMCODE

    AND T0.ItmsGrpCod = @ITEMGROUP

    WHERE (w.WHSCODE >= @F_WAREHOUSE AND w.WHSCODE <= @T_WAREHOUSE)

    OR (@F_WAREHOUSE = '' AND @T_WAREHOUSE = '')

    The arithmetic appears to be fairly simple, I can't see any reason why it can't be done in the output.

    This is just the first phase. The output of this first chunk of the function is used to drive a second bank of nested cursors which perform more calculations.

    This looks like a VB programmer's first attempt at TSQL coding. Get a professional in to write it properly.

    “Write the query the simplest way. If through testing it becomes clear that the performance is inadequate, consider alternative query forms.” - Gail Shaw

    For fast, accurate and documented assistance in answering your questions, please read this article.
    Understanding and using APPLY, (I) and (II) Paul White
    Hidden RBAR: Triangular Joins / The "Numbers" or "Tally" Table: What it is and how it replaces a loop Jeff Moden