Active Server Pages |
Home > ASP > |
Stored Procedures for ASP and VB ProgrammersBy Benny Alexander The article is indented towards ASP and VB Programmers who always write hard core SQL statements inside their coding to communicate with database. If you read this article, Its time for you to learn and switch over into Stored Procedures. You can find a no of resources on stored procedures, But unlike others in this tutorial I tried to give you the maximum possible information , from the Theory to the debugging of stored procedures. I can always update this if you give your valuable suggestions. Write me to Benny@macronimous.com Requirements: Programming knowledge in ASP or VB, MS SQL server & Database concepts. When I was starting my carrier as a VB programmer, All I knew to connect a Database with my front-end are, the Data control and RDO. Later When I moved to ASP, I was enjoying writing SQL statements. It was fun when the SQL statements were simple and struggle when it comes to complex and nested queries. Writing direct SQL commands inside my VB or ASP program were not a big issues to me, until I started thinking about Performance of my applications. But when time came, I started learning Stored Procedures I was really encouraged to do possible refactoring of my previous coding with Stored Procedures, and my life with direct SQL commands came to an end. I hope my SP(Stored Procedure) history was not boring. With an assumption that you are good in ASP or VB and SQL let us begin SPs. What are Stored Procedures?SPs are an advanced
feature in SQL server that offers you to create, compile and run SQL
statements in the server itself, to isolate your business logic from
data logic and to improve the performance of your application. Why write Stored procedures?1.Mainly to increase the performance and the momentum to our programs. When you write a stored procedure, it will be pre-compiled by the SQL server, so that it can increase the speed of executing the queries and hence your application. When you write a stored procedure the database(DB) server automatically generates an execution plan for the procedure. The plan will be updated whenever a change is made in the procedure by the DB server. 2.You can take away all your SQL commands so that the data logic can be isolated from your business logic(ie.,Coding). This kind of encapsulation helps the web server to read and interpret lengthy and complex SQL commands. 3.Then like COM, stored procedures can be reused. For example if you want to do the same query in two different ASP pages or in VB forms, you can reuse the stored procedure which you have written for one page, It saves you time. 4.The application code as well as the stored procedure code are becoming easy to maintain. Updating a stored procedure may not affect the other part of an application or user who uses the same stored procedure. 5.The queries can be customized by using input/output parameters, like functions and procedures which you write in your programming languages. What are the types of Stored Procedures?There are three types of stored procedures. Microsoft supplies several stored procedures to manipulate and administrate the database. Apart from them can write custom stored procedure to use them in our application level. 1. System stored
procedures:
will list the files in the root directory of C
drive. Where to write Stored Procedures?You can
write Stored Procedures in the following possible ways,
2. Using Query
Analyzer - Open query analyzer,
select the DB, type the procedure and execute it.
Starting Stored ProceduresNow let us see an example procedure and peek into it a while for the basic understanding and structure of any stored procedure. I prefer enterprise manager to write stored procedure, and during the time of learning I recommend you to use Enterprise manager.
After tying the procedure you can immediately check the syntax. Here all the SQL commands will be written in the BEGIN...END block. Here sp_selauthor is the procedures name. All about parametersWe
have seen a simple stored procedure that just selects the required
values from a table. Now let us see a little more complex stored
procedure with parameters. Stored procedures allow input and
output(i/o) parameters to have a better control over the i/o
values.
....................[EXAMPLE1] In the above example, @publisher_name is the input parameter and the values will be sent by your ASP or VB code. We will see, how to send values shortly. Another example , an Insert statement, with two input parameter can help us to understand better.
....................[EXAMPLE2]
....................[EXAMPLE3] Here, the total no of authors who write for WROX press will be counted and sent through the output parameter. You can see the keyword OUTPUT to differentiate the output parameter from the input parameter. Calling Stored procedures from your ASP codeNow let us call the stored procedure from ASP code. I will take stored procedure EXAMPLE2, to explain.
The line ObjConn.Excecute runs the SP from the ASP
code. Hope you understand how simple it is.
You may need a little explanation on the above
written ASP code. Here I create a command object objCmd, and setting
the parameters. The name of the returned variable is "@count_authors", which is also mentioned in the
stored procedure. The type of this variable is integer with length
4. When I execute the SP, sp_sel_no_authors, I get the return value, as
output which can be displayed in the web page. I hope this two examples are sufficient enough for ASP
programmers. Now let us turn to VB.
Calling Stored procedures from your VB codeIf a stored procedures that do not return records (or rows) can be executed from Visual Basic with the ExecuteSQL() method as follows. That means we can not use this method with SELECT statements. But if the the SQL statement returns records then we need to use a Dynaset or Snapshot to capture the values. The following returns a set of recordset values using a Data control.
Another example can give you better understanding with stored procedures that return values and that not return values.
Handling errors in stored proceduresIn this section we will cover the necessary
information you need to know about finding and dealing errors in a
stored procedure during the time of execution. In fact there are
about 3800 SQL server error messages, which are maintained in the
master catalog's "sysmessages" table. Every error message has its
own severity level and it ranges from 0 to 25, depending on how bad
the error is.
As this table doesn't exist the SQL server raises a
Fatal Error and the execution of the procedure terminates. So the
PRINT statement will not be executed and we will not get the error
message 'Table Does not exist'. Instead we get the error message
raised by the Server. With one example the nonfatal errors can be illustrated. Let us assume that you are trying to Insert NULL value to a filed which is designed a Primary key. This will raise a non fatal error and will allow you to execute the entire procedure. In three ways you can get the catch the
errors
in Stored procedures. Using @@ERROR,
SP_ADDMESSAGE, and RAISERROR functions within SQL the Server. Let us
discuss the one by one.
In this example the IF...ELSE statements test @@ERROR after
an INSERT statement which inserts the employee details in a stored
procedure. The value of the @@ERROR variable determines the return
code sent to the calling program, indicating the success or failure
of the procedure.
Here, [@msgnum =] msg_id is the ID of the message;
[@severity =] is the severity level of the error (severity is
smallint) and value varies from 0-25 as mentioned earlier; [@msgtext
=] 'msg' is the text of the error message; [@lang =] 'language' is
the language for this message, which helps to display the error
message in multiple languages. [@with_log =] is whether the message
is to be written to the Microsoft® Windows NT® application log when
it occurs, the value will be true or false. [@replace =],If
specified as the string REPLACE, an existing error message is
overwritten with new message text and severity level.
The RAISERROR method: The syntax for RAISERROR menthod is as follows,
Hope we have discussed sufficiently, to start with stored procedures. To practice more, you can expand your applications with Indexes, Triggers etc.,. Meanwhile, I will cover SPs in another article for ASP.NET and VB.NET developers. Write your comments to improve this article to . |