I was brought up in the world of programming to always use stored procedures when accessing a database from a client program. The advantages were clear I was told:
- The stored procedure was pre-compiled and therefore would run more quickly.
- The store procedure provided better security through the use of the keyword GRANT.
- The stored procedure protected against SQL injection attacks.
- The stored procedure easily allowed me to pass parameters to my T-SQL.
Plus, let me give countering views to the four points I listed above in favor of stored procedures:
- I am not so sure actually that the store procedure is precompiled. Possibly someone can point me to a link that clears this this issue up for me. I have heard arguments both for and against when it comes to SQL Server. Regardless, when you are running a simple select statement the time that it would save is inconsequential to the performance of your overall application. Hence, this is a moot point.
- This is not true when .Net security is used correctly, especially when the right user permissions for the process running the application is in concert with Windows Integrated Authentication. Also SQL Server 2005 adds extended functionality to schemas, which can restrict the connecting client application to only access certain tables and perform certain functions.
- This point seems deceivingly true. But when looked at more thoroughly, if a hacker is able to exploit a poorly written T-SQL statement in your code they will be able to equally do so even if it is contained in a stored procedure. The answer here is to validate all user input and to carefully write all T-SQL statements.
- This point is true at first but again becomes moot when you learn how to pass parameters to a T-SQL statement in your code.