Some comments on Stored Procedures
Friday, October 24th, 2008There are many advatages of stored procedures. some of them are:
- Procedures are on the server so messages don’t need to go back and forth to the client during the time the procedure is executed.
- Procedures are parsed once, and the result of the parsing is stored persistently, so there’s no need to reparse for every execution.
- Procedures are in the catalog so they are retrievable, and procedures are subject to security provisions, in the same way as other SQL data.
- Procedures are in one place so code sharing is easy, and when changes happen there’s no need to send code changes to clients.
When you use a stored procedure, you are depending on cache (which is limited) and access to the procedure (which may be serialized). Therefore it is a mistake to use stored procedures too frequently .
Some of the important points we should remember while creating the store procedure are.
- Don’t declare parameters to be “input/output” when they’re merely “input” parameters.
- Don’t write stored procedures as if the precompiler has the built-in skills of a compiler. Take things out of loops, fold, put declarations together in one statement, and avoid testing assumptions on your own—don’t expect the DBMS to do these things for you.
- Shift logic from WHERE clauses to IF clauses whenever possible.
- If a stored procedure contains an IF statement and is inside a trigger, take the condition out of the IF and put it in the trigger’s WHEN clause.
- avoid putting COMMIT or ROLLBACK in the stored procedure. The transaction-end statements are especially bad if you’re using distributed transactions and TP monitors