• I'm not suprised it took a couple of hours looking at the query you have loops with cursors which is going to drag performance down into the basement and beyond then on top of that the SQL function reads like a VB program function.

    A couple of blatently obvious things apart from all the loops and Cursors, things that are going to kill this include this type of thing.

    SET @ST_DATE = (SELECT TOP 1 DOCDATE FROM OINM ORDER BY DOCDATE)

    SET @EN_DATE = (SELECT TOP 1 DOCDATE FROM OINM ORDER BY DOCDATE DESC)

    Thats two queries with a sort operator, and they can be better expressed, on top of that this is run again in the next block, which is superflous as I cannot see where the @ST_DATE, and @EN_DATE changes in the interim.

    SELECT @ST_DATE=MAX(DOCDATE), @EN_DATE=MIN(DOCDATE) FROM OINM

    Evaluate the Top part on its own and then evaluate the second query I'll put money on the second part of code beating the top one.

    In short this needs a total rewrite so that its less procedural and more Set based.

    _________________________________________________________________________
    SSC Guide to Posting and Best Practices