SQL Server 2005 Stored Procedures TutorialPart 1I've been using databases for years, and I have a good knowledge of SQL, but for some reason I always viewed Stored Procedures as being only for the experts. But nothing could be further from the truth. In fact, if you really want to get some work done with SQL Server, and you want a robust system that separates out the user interface of your program from the underlying database logic, then you need stored procedures right now. So what are stored procedures?A stored procedure is a sequence of SQL command that are stored in the database and given a name. A stored procedure acts like a function in a programming language, taking parameters in and returning data as a result. Here is a simple example of a stored procedure:
The first line tells SQL Server to make a new stored procedure called get_houses_by_color. This procedure is defined as having one parameter (called color) which is a varchar(10) defaulting to 'red'. The second and third lines define the body of the procedure, which in this case is just a simple select command. See how the @color parameter is used in the body of the procedure, just like a variable in a programming language. To run the stored procedure, type:
and the procedure will be executed, returning as a table with three columns (ID, name, location) with one row for each house of the chosen colour. The result of this stored procedure is no different from what you would get if you just executed the select statement directly. So what's the big deal?Storing this SQL select statement as a stored procedure is good because:
Trying them outIf you make a stored procedure, then find a bug in it and try to define it again, you'll get an error. Use the following approach to check if it exists and drop it first, before defining it:
Where are stored procedures actually stored?Stored procedures are stored in the system table called syscomments. You can view an existing stored procedure by typing:
The command
lists all stored procedures that are currently defined. Specifying and using more than one parameter:Multiple parameters can be passed to a stored procedure in one of two ways (a little like VB):
What can they do for me?Stored procedures can do anything that SQL statements can do, and a little more besides. You can use them to add new records, perform queries, update data and delete data. Read on...In part 2 of this article, I give many example stored procedures to demonstrate their power. |