I found that SQL stored procedures are very interesting and useful. I have written stored procedures but i want to write well crafted, good performance tuned and concise SPs for any sort of requirement and also would love to learn about any tricks or good practices for stored procedures. How do i move from the beginner to the advanced stage in writing stored procedures?
Update: Found from comments that my question should be more specific. Everyone has some tricks upon their sleeves and I was expecting such tricks and practices for SPs which they use in their code which differentiates them from others and more importantly spruce up the productivity in writing and working with stored procedures.
In Object Explorer, connect to an instance of the SQL Server Database Engine, expand that instance, and then expand Databases. Expand the database that you want, expand Programmability, and then expand Stored Procedures. Right-click the user-defined stored procedure that you want and select Execute Stored Procedure.
The syntax to create a stored procedure in SQL Server (Transact-SQL) is: CREATE { PROCEDURE | PROC } [schema_name.]
Here are my stored procedure error-handling guidelines.
When executing a stored procedure, always check both @@error and the return value. For example:
EXEC @err = AnyStoredProc @value SET @save_error = @@error -- NULLIF says that if @err is 0, this is the same as null -- COALESCE returns the first non-null value in its arguments SELECT @err = COALESCE( NULLIF(@err, 0), @save_error ) IF @err <> 0 BEGIN -- Because stored proc may have started a tran it didn't commit ROLLBACK TRANSACTION RETURN @err END
Always store and check @@error after the following statements:
INSERT, DELETE, UPDATE SELECT INTO Invocation of stored procedures invocation of dynamic SQL COMMIT TRANSACTION DECLARE and OPEN CURSOR FETCH from cursor WRITETEXT and UPDATETEXT
The only trick I always try to use is: Always include an example usage in a comment near the top. This is also useful for testing your SP. I like to include the most common examples - then you don't even need SQL Prompt or a separate .sql file with your favorite invocation, since it's stored right there in the server (this is expecially useful if you have stored procs that look at sp_who output for blocks or whatever and take a bunch of parameters).
Something like:
/* Usage: EXEC usp_ThisProc @Param1 = 1, @Param2 = 2 */
Then to test or run the SP, you simply highlight that section in your script and execute.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With