• Hi Luis

    As Eugene said, this could be replaced without using a cursor with something like the following.

    This example may not be the best way to do it, but it has the elements from you procedure sort of replicated to make it a bit easier to follow.

    Also as I have nothing to test this against I can't guarantee that it will even work :ermm: (may have some typos or logic errors)

    ;with

    -- Using the query for the cursor

    cursorReplacement AS (

    SELECT referencia, TAMANHO, LEFT(NEWID(),23) as sgtstamp,

    min(QTD) AS SORTIMENTO,

    ROW_NUMBER() OVER(PARTITION BY referencia ORDER BY referencia,tamanho ASC) AS Rownumb

    FROM arttamcor WHERE referencia = '30110'--IN('29913','30110')

    GROUP BY referencia, TAMANHO

    ),

    -- select the tam for each row in the cursor replacement. Only used for the NOT EQUAL query

    tam as (

    select isnull(tam,'#') tam

    from sgt s

    left outer join cursorReplacement c ON s.ref = c.referencia

    where tam = 'Y'

    ),

    -- return a row for insert from cursor replacement with tam set to 'Y'

    tamanhoNEtam AS (

    select sgtstamp, referencia as ref, 'Y' as tam,

    rownumb as pos, sortimento as dimcol,

    CONVERT(date,GETDATE()) as ousrdata,CONVERT(time, GETDATE()) as ousrhora,'ADM' as ousrinis,

    CONVERT(date,GETDATE()) as usrdata,CONVERT(time,GETDATE()) as usrhora,'ADM' as usrinis

    from cursorReplacement c

    where not exists ( select 1 from tam t WHERE t.tam = c.tamanho )

    ),

    -- return a row for the insert from the cursor replacement (covers the second insert for the IF NOT EQUAL as well as the IF EQUAL insert)

    tamanhotam AS (

    select sgtstamp, referencia as ref, tamanho as tam,

    rownumb as pos, sortimento as dimcol,

    CONVERT(date,GETDATE()) as ousrdata,CONVERT(time, GETDATE()) as ousrhora,'ADM' as ousrinis,

    CONVERT(date,GETDATE()) as usrdata,CONVERT(time,GETDATE()) as usrhora,'ADM' as usrinis

    from cursorReplacement c

    )

    -- INSERT INTO SGT(sgtstamp, ref, Tam,pos,dimcol, ousrdata, ousrhora, ousrinis, usrdata, usrhora, usrinis)

    SELECT *

    FROM tamanhoNEtam

    UNION ALL

    SELECT *

    FROM tamanhotam