Using sprocs or ad-hoc sql
I use stored procedures "religiously" when developing data-centric applications and I'm always interested as to why people who use SqlServer would want to use ad-hoc sql; I think that the main reason is probably is the perception of "duplicating effort".
Anyway, I just read an interesting thread about the use of stored procedures in which the following list of reasons came up for using stored procs:
- this way you can keep your SQL code out of your C# code
- very often you can hide your changes to DB schema from your code by modifying only your SPROC
- If you use particular query in many points of the application, you can reuse it
- The SPROC is more efficient - your SQL is precompiled before first use and stored until DB restart or explicit recompile - and when you use ad-hoc queries, the DB engine has to preprocess query each and every time
- You can easily use many different T-SQL language constructs, like conditionals, cursors etc.
Whilst they are true I think that the second point there is the most important one of those followed by point one. The other 3 issues including the issues surrounding perf. are probably not really all that relevant - particularly the perf. issue.
For me, the biggest reason to use stored procedures has been for the security issues surrounding sql injection attacks, but as mentioned in the post that I read you can also use parameter placeholders so that you get the benefit of parameter checking and also be able to inline queries (but changing a query now requires a recompile of the whole app).
Mind you, I still find that readability of stored procedures is better - and hence easier for me to maintain - when separated from code.
Original Post: http://weblogs.asp.net/Toffer/archive/2005/03/07/387700.aspx