stored procedure vs individual insert statements

  • Why is it that if I run the individual insert statements in Example A one at a time, the overall time to run is 20 minutes. If I put all of the insert statements into a stored proc, it takes an hour and a half? Same inserts.

    Example A

    insert into prod1

    select *

    from test1

    insert into prod2

    select *

    from test2

    insert into test3

    select *

    from test3

    etc

  • What happens if you execute those inserts in a batch?

    _____________
    Code for TallyGenerator

  • Pardon for my ignorance but what do you mean by batch?

  • I mean executing all 3 statements in one go but without wrapping it in a procedure.

    Just as you pasted it here.

    _____________
    Code for TallyGenerator

  • Is it a typo, or are you really intending on selecting the same table into itself?

    I've noticed this on occasion as well (something runs well/as expected in query analyzer, but the moment it is a procedure, performance plummets). Perhaps greater SQL minds than mine have some insight into this problem. These are just my random musings, but I wonder if it has something to do with transaction management/locking and latching. I wonder if wrapping each statement in a begin tran/commit block would help, since it would force out writes to the transaction log.

    The other thing is if you are really selecting the same table into itself, depending on its size, consider copying out the records to a temp table, and copying them back in to prevent contention or latching or locking to the table. SQL Gurus, please step in if I've misstated something here, because this area has always been somewhat of a mystery to me.

    Hope this at least sparks some interesting thought.

    Thanks!

  • Jeremy,

    there is no any point in wrapping each statement in a begin tran/commit block because they are transactions anyway.

    And I would guess that was a typo.

    I really doubt real tables have got such funny names. 🙂

    Regarding this I would say that devil is usually in details.

    Posting real statements could be very helpful.

    The real reason could be anything we don't see: misuse of parameters, remote calls, even typo in script.

    _____________
    Code for TallyGenerator

  • Can u pls paste those queries here so that v can check if they need some fine tuning or u can check if ur tables r indexed properly.

    All this while I was under the impression that stored procedures run faster cuz they r pre compiled. Correct me if I'm wrong.

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

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