DIfference Between Stored Procedures and Prepared Statements?

后端 未结 3 2040
感动是毒
感动是毒 2020-12-04 14:50

What is the difference between Stored Procedures and Prepared Statements... And which one is better and why...!! I was trying to google it but haven\'t got any better articl

3条回答
  •  执笔经年
    2020-12-04 15:12

    The other answers have hinted at this, but I'd like to list the Pros and Cons explicitly:

    Stored Procedures

    PROS:

    1. Each query is processed more rapidly than a straight query, because the server pre-compiles them.
    2. Each query need only be written once. It can be executed as many times as needed, even across different sessions and different connections.
    3. Allows queries to include programming constructs (such as loops, conditional statements, and error handling) that are either impossible or difficult to write in SQL alone.

    CONS

    1. Require knowledge of whatever programming language the database server uses.
    2. Can sometimes require special permissions to write them or call them.

    Prepared Statements

    PROS

    1. Like stored routines, are quick because queries are pre-compiled.

    CONS

    1. Need to be re-compiled with each connection or session.
    2. To be worth the overhead, each prepared statement must be executed more than once (such as in a loop). If a query is executed only once, more overhead goes into preparation of the prepared statement than you get back since the server needs to compile the SQL anyway, but also make the prepared statement.

    For my money, I'd go with Stored Procedures every time since they only need to be written and compiled once. After that, every call to the procedure leads to saved time, whether you're on a new connection or not, and whether you're calling the procedure in a loop or not. The only downside is needing to spend some time learning the programming language. If I didn't have permissions to write stored procedures, I would use a prepared statement, but only if I had to repeatedly make the same query multiple times in the same session.

    This is the conclusion I've come to after several months of off-and-on research into the differences between these two constructs. If anyone is able to correct bad generalizations I'm making, it will be worth any loss to reputation.

提交回复
热议问题