Problems with SET ROWCOUNT

  • Hi All,

    I have a simple query and I would like to use Rowcount to do abtch updates, the problem I am having now is that the update happens only once.

    Set @sql = '

    SET ROWCOUNT 50000

     Update tmp

      Set tmp.Profiled = ''Y''

     from TMP tmp

      inner join dbo.TB_PersonProfile MRT

     on tmp.route = MRT.personurn

      iNNER JOIN CompanyPRofile CP

     on mrt.name = CP.name

      where CP.operator  = ''DLL''

    SET ROWCOUNT 0

    '

    Can anyone help please.

    Thanks  


    Kindest Regards,

    John Burchel (Trainee Developer)

  • That doesn't need to be dynamic sql at all.  This works perfectly :

     

    SET ROWCOUNT 10000

    WHILE 1=1 --Be careful with this you don't want an infinte loop!

    BEGIN

        UPDATE myTab

            SET myCol = @newVal

    SET Updated = 1

        WHERE mycol <> @newVal AND Updated = 0

        IF @@ROWCOUNT = 0

            BREAK

    waitfor delay 00:00:02 --wait 2 seconds before running again

    END

    SET ROWCOUNT = 0

  • Or maybe this could eliminated a costly join :

     

    create table ttemp

    (

    id primary key clustered

    )

    insert into ttemp (id) select id from tmain

    set rowcount 10000

    while @@rowcount > 0

    begin

    update tmain set col = 'wathever'

    from tmain inner join ttemp on tmain.id = ttemp.id

    delete from ttemp

    --would have to check to make sure this process updates and delete matching rows too!!

    end

    set rowcount 0

    --check if new rows where inserted and update if needed... or set a new rule/default beforehand

    drop table ttemp

  • thanks all for your answers.

    I have a problem, I have a table which has an identity column, and I want to do batched updates, i.e update row 1 - 50, 50 - 100 right all the way to the end.

    Does anyone have any idea as to how to do this ?

     


    Kindest Regards,

    John Burchel (Trainee Developer)

  • Very simple way :

    Add a column IsUpdated

    SET rowcount 50

    while @@rowcount > 0

    begin

    update dbo.table set IsUpdated = 1, YourCol = 'Whatever' WHERE IsUpdated = 0

    end

    SET rowcount 0

  • Hi

    I ran  a test using one of the code displayed above, but I was inserting into a table using rowcount, and it just kept inserting over and over again without stopping.

     

    Table1 = 10m rows

    Table2 = empty

    I want to insert into Table2 in abtches of 10000, I used the idea above and it just kept inserting and inserting like an indefinite loop


    Kindest Regards,

    John Burchel (Trainee Developer)

  • Can't be sure without the code, but I'm guessing that you are not updating a flag column, nor are you keeping the last record inserted.  Both which would allow you to break the loop eventually.

Viewing 7 posts - 1 through 6 (of 6 total)

You must be logged in to reply to this topic. Login to reply