Web design, SQL, and .NET for the young, up-and-coming developer - Dot Net Yuppie - Blog Archive » The Top Ten Reasons for Consistently Using Stored Procedures
Web design, SQL, and .NET for the young, up-and-coming developer Dot Net Yuppie
  1. Protection against injection attacks All data that is passed to a stored procedure is passed as a parameter with a specific data type. Assuming you don’t dynamically build SQL queries within a stored permission, the likelihood of an injection attack on a stored procedure is slim to none. In all fairness, dynamic SQL queries written within ASP.NET can be executed using parameters, but parameters aren’t required. Making stored procedures a requirement ensures that everyone on your team is protecting against injection attacks.

    Consider the following two examples:

    Dim UserInput As String = "1'); DELETE FROM tblInjectionAttack;"
    Dim SQL As String
    SQL = "INSERT INTO tblInjectionAttack (Column1) VALUES ('" & UserInput & "')"
    		
    CREATE PROCEUDRE InsertInjection
    	@UserInput NVARCHAR(500)
    AS
    	INSERT INTO tblInjectionAttack (Column1) VALUES (@UserInput)
    	--EXEC InsertInjection '1''); DELETE FROM tblInjectionAttack;'
    		

    In the first example, the SQL query will be injected and the attacker will be able to execute any command that they have access to. In the second example, the attacker’s SQL injection will be saved in Column1 and won’t be executed at all.

  2. Better database security Stored procedures allow for a reduction of privileges for the database account that ASP.NET uses. You can restrict your database account to only have permissions to execute stored procedures, and restrict its access to everything else. If the database account becomes compromised, the attacker will have much less power to do damage — he won’t be able to see or modify any tables, and won’t even be able to get a list of stored procedures. Generally speaking, the fewer users with elevated privileges the better.

    If you create a new user in a database, by default, that user has no privileges; however, if you need to remove existing privileges from an account, you can do so by executing the following query:

    --To deny access on one single table:
    DENY SELECT,INSERT,UPDATE,DELETE ON [TableName] TO [Username]
    
    <span id="more-11"></span>
    
    --To deny access to all existing tables,
    --execute the printout of the following query:
    DECLARE @Username NVARCHAR(256)
    SET @Username = 'JoeUser'
    DECLARE @StoredProcedure NVARCHAR(256)
    DECLARE cursor_sp CURSOR FAST_FORWARD FOR
    	SELECT name FROM sysobjects WHERE xtype = 'u'
    OPEN cursor_sp
    	FETCH NEXT FROM cursor_sp INTO @StoredProcedure
    		WHILE @@FETCH_STATUS = 0
    		BEGIN
    			PRINT 'DENY SELECT,INSERT,UPDATE,DELETE ON '+@StoredProcedure+' TO '+@Username
    			PRINT 'GO'
    			FETCH NEXT FROM cursor_sp INTO @StoredProcedure
    			--Note: You may use EXECUTE() instead of PRINT if you
    			--		want the procedure to execute the command for you
    		END
    CLOSE cursor_sp
    DEALLOCATE cursor_sp
    		

    Once an account’s privileges have been removed, you can give it EXECUTE permissions using the following query:

    --To grant EXECUTE on one single stored procedure:
    GRANT EXECUTE ON [StoredProcedureName] TO [Username]
    
    --To grant EXECUTE on all existing procedures,
    --execute the printout of the following query:
    DECLARE @Username NVARCHAR(256)
    SET @Username = 'YourUsername'
    DECLARE @StoredProcedure NVARCHAR(256)
    DECLARE cursor_sp CURSOR FAST_FORWARD FOR
    	SELECT name FROM sysobjects WHERE xtype = 'p'
    	OPEN cursor_sp
    		FETCH NEXT FROM cursor_sp INTO @StoredProcedure
    			WHILE @@FETCH_STATUS = 0
    			BEGIN
    				PRINT 'GRANT EXECUTE ON '+@StoredProcedure+' TO '+@Username
    				PRINT 'GO'
    				FETCH NEXT FROM cursor_sp INTO @StoredProcedure
    				--Note: You may use EXECUTE() instead of PRINT if you
    				--		want the procedure to execute the command for you
    			END
    	CLOSE cursor_sp
    DEALLOCATE cursor_sp
    		
  3. Easier to maintain Stored procedures can be modified without having to recompile your ASP.NET application, and you don’t have to wade through ASP.NET code to get to the SQL code you want to modify.
  4. Verification of code SQL won’t allow you to create or update a stored procedure if it contains certain type of errors (e.g. if it references invalid objects or contains typos, etc.). ASP.NET doesn’t verify dynamic SQL statements, so if you have a minor typo, you’ll waste time compiling your project and tracking down your error.
  5. Easier to read Going along with easier to maintain, a complex, syntax-highlighted stored procedure is much easier to read than an ASP.NET string concatenation that contains a flurry of ampersands and quotes intertwined with .NET markup. Simpler queries aren’t such a problem, but I think you can appreciate how dynamic queries can turn complex SQL statements into a nightmare to debug and manage.
  6. Can be tested separate from ASP.NET You can design and manage stored procedures within an SQL management application (like Microsoft SQL Server Management Studio). Conversely, dynamic queries force you to be in ASP.NET and you have to run them within the environment of your application, and you’ll have to recompile your application each time you want to test a query. Less compiling and less overhead means you’ll get your job done faster and with less effort.
  7. Reuse code Depending on the type of stored procedure (and how you decided to code it), you may be able to reuse the same procedure over multiple applications. The ability to reuse code means you’ll be more efficient and can spent more time on other areas of a project.
  8. Layer abstraction It’s advantageous to separate your database logic (stored procedures) from your presentation (ASP.NET). Layer abstraction is sometimes even necessary, such as a project where the database and .NET development are handled by different developers. There’s a reason why HTML has CSS and why .NET has code-behind — because layer abstraction makes development cleaner and easier.
  9. Improved performance I’ve read plenty of blogs debating the performance benefits of stored procedures over dynamic queries, but regardless, there is at least potential for benefit. Stored procedures are “pre-compiled” (they have a cached execution plan), which should offer performance benefits over dynamic queries. Whether or not a performance benefit exists from a cached execution plan, reason #10 does offer a marked performance benefit.
  10. Reduced data transfer When ASP.NET executes a dynamic SQL statement, it must transfer the entire query to the database. If the query exists on the database (in the form of a stored procedure), ASP.NET only has to transfer the name of the stored procedure and any parameters associated with the procedure. In my opinion, the bandwidth and transfer time saved from stored procedures is reason enough to strictly use stored procedures in almost all situations.

3 Responses to “The Top Ten Reasons for Consistently Using Stored Procedures”

  1. Ivan Atanasov Says:

    Very nice article boy. How you can write stored procedures, if you develop reporting tools?

  2. DotNetYuppie Says:

    I’ll usually write stored procedures within Microsoft SQL Server Management Studio and save a collection of stored procedures as an SQL file. By keeping my stored procedures within an SQL file, it allows me to keep the formatting and comments of all of my procedures.

    It’s probably not the cleanest method, but it also allows me to search through my stored procedure code very easily.

  3. stefan Says:

    I agree with you. Sp:s adds a layer of abtraction and in bigger projects it’s invaluable to keep coders from doing mistakes (which is so easy to do when using dynamic sql). Say for example they write do a “update bla set created=getdate(), foo=…” when “created” column should just be set on inserts etc. The actual data is a companies biggest asset (not the app) and all means of keeping consistency should be taken.

Leave a Reply