0% found this document useful (0 votes)
25 views12 pages

Unit 5

The document discusses stored procedures in SQL, including: - Stored procedures allow SQL statements and logic to be saved in a database for repeated execution. They can contain one or more SQL statements like SELECT, INSERT, UPDATE, DELETE. - Benefits of stored procedures include reducing network traffic, improving performance by executing multiple statements at once, and increasing security by restricting access to data. - Stored procedures can be created using SQL syntax and executed from applications using ADO Connection and Command objects. Parameters allow values to be passed into and returned from stored procedures.

Uploaded by

sheenafarhana03
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
25 views12 pages

Unit 5

The document discusses stored procedures in SQL, including: - Stored procedures allow SQL statements and logic to be saved in a database for repeated execution. They can contain one or more SQL statements like SELECT, INSERT, UPDATE, DELETE. - Benefits of stored procedures include reducing network traffic, improving performance by executing multiple statements at once, and increasing security by restricting access to data. - Stored procedures can be created using SQL syntax and executed from applications using ADO Connection and Command objects. Parameters allow values to be passed into and returned from stored procedures.

Uploaded by

sheenafarhana03
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 12

UNIT-5

WORKING WITH THE COMMAND OBJECT


Stored procedure:
 Stored procedures are SQL statement that are syntax – checked complied and stored
in database
(or)
 A procedural language is language that allows you to write code logic and then save it
the saved logic is known as stored procedure visual basic is an example of procedural
language
 A stored can contain one or more SQL statement such as the familiar SELECT
INSERT UPDATE and DELETE statement
 It also contain transaci-SQL statement transaci -SQL is microsoft ‘s extension to the
SQL language
 Microsoft SQL server support the stored procedure concept but ms-access doesn,t
support stored procedure

BENFITS OF USING STORED PROCEDURE:


 If there is a complicated set of SQL statement to be executed on multiple active server
pages these can be placed in a stored procedure and the procedure executed instead
this reduces the size of the asp page and ensures that the same SQL statement are
executed for each pages
 Executing a series of SQL statement in a stored procedure is much more afficent than
executing the same series of statement in an asp page multiple tripa back and forth
between the web server and the database server can be avoided
 Values can be passed both to and from a stored procedure this means that stored
procedure can be very flexible the same stored procedure can return very different
information depending on the data passed to it before it ran
 When a collection of SQL statement is passed to the database server each of the
statement must be passed individually from the asp page to the database when a stored
procedure is executed on the other hand only a single statement is passed from the
ASP page to the database (i.e the call to the stored procedure) by using stored
procedures network traffic can be reduced
 A table premissions can be configured in such a way that user can modify a table only
by using a stored procedure this can improve the security of data in database tables
 A stored procedure can be executed from within another stored procedure this strategy
enables bulding complex stored procedures from smaller ones this also makes that the
same stored procedure can be reused for many different programming tasks
THE SYNTAX OF STORED PROCEDURE:
 The following shows the code for creating a stored procedure in SQL server

CREATE PROCEDURE stored_procedure_name


{
@p_arugment1 datatype1
@p_argunment 2 datatype 2
@p_argunment 3 datatype3
)
AS
………
………
Return(0)
Example:
CREATE PROCEDURE getFirstName
(
@first name VARCHAR(20)
)
AS
SELECT @first name=au_fname FROM authors
The syntax for executing a siored procedure
 To execute a stored procedure use the following syntax

Example

CREATING STORED PROCEDURES:


 A new stored procedure can be using Microsoft Query Analyzer (formerly known as
I/SQL), Microsoft SQL Server Enterprise Manager, or with Active Server Page script.
In all three cases, the stored procedure is actually created with the SQL CREATE
PROCEDURE statement.
 A SQL stored procedure can contain a single Transact-SQL statement or hundreds of
statements (the maximum permissible size of a stored procedure is 128 megabytes)
 The following example that creates a very simple stored procedure is
CREATE PROCEDURE getAuthors AS select*from authors
 If the above statement is executed, a stored procedure named getAuthors is
created. This stored procedure retrieves all the rows from the table named
Authors.
 Stored procedure can also be created with the following ASP script
<! -- #INCLUDE FILE = “adovbs.inc” -- >
<%
Set con = server. createobject(“ADODB .connection”)
con.open”FILE NAME = c:/myDataLink.UDL;DATABASE = Authors”
con.execute “CREATE PROCEDURE getauthors AS select*from authors”
%>
After the stored procedure has been created, on execution, it will return a list of authors
within Microsoft Query Analyzer. A good way to test a procedure before it is called from
an ASP script is to execute a stored procedure with in the Query Analyzer. Use the
EXECUTE statement as follows.
EXECUTE getAuthors
DESTROYING A STORED PROCEDURE
 To remove or delete a stored procedure, use the following syntax
DROP PROCEDURE stored_procedure_name
Example
DROP PROCEDURE getAuthors
Creating Stored Pocedures With Parameters
 Data can be passed back and forth to a stored procedure by using return codes, input
parameters, and output parameters.
 The following examples creates a procedure, named checkAuthors, which uses a
return code to indicate whether an author named ‘Green’ exists or not in the table
Authors
CREATE PROCEDURE checkAuthor
AS
IF EXISTS (SELECT au_Iname FROM authors WHERE au_Iname = ‘Green’)
RETURN (1)
ELSE
RETURN (0)
 When the RETURN statement is executed in the above procedure, the procedure
is exited and a return code is passed out from the procedure. The procedure
returns the value 1 if the author named Green exists, Otherwise, the procedure
returns the value 0
EXECUTING STORED PROCEDURE WITH THE CONNECTION OBJECT
 The simplest way to executed a stored procedure within an Active Server
Page is by using the Connection object.
 A SQL stored procedure can be executed just as any other SQL statement.
For example, the following Active Server Page script executes a stored
procedure named byroyalty
 Example : 1
<!--#INCLUDE FILE = “adovbs.inc”-->
<%
Set con = server.createobject(“ADODB .connection”)
Con.open “FILE NAME = c:\myDataLink.UDL;DATABASE = Authors”
Set RS =con.execute (“byroyalty 25”)
While not RS.EOF
Response .write RS (“au_id”)&”<br>”
RS.movenext
Wend
%>
 The byroyalty procedure is stored in the Authors database. The byroyalty
procedure accepts a single input parameter that represents a certain royalty
percentage and returns a list of authors IDs for the authors who are receiving that
royalty percentage.
OUTPUT
724-80-9876
899-46-2345
Example: 2
 The connection object can be used to execute a stored procedure that simply adds
or updates data in a database table. Consider the following stored procedure
CREATE PROCEDURE addcustomer
(
@ custid VARCHAR (15),
@ name VARCHAR (15),
@ emailid VARCHAR (30)
)
AS
INSERT into customers (custid, name, emailid)
VALUES (@custid, @name, @emailid)
 The above stored procedure accepts 3 input parameters, customers identity
number, customer name and customers emailed and inserts the value of the
parameters into the customers table. To execute this stored procedure, the
following scripts can be used
<! -- #INCLUDE FILE = “adovbs.inc”-->
<%
Set con = server.createobject(“ADODB.connection”)
Con.open “FILE NAME = c:\myDataLink.UDL;DATABASE = Authors”
Con.execute “addcustomer ‘1’, ‘Senthil’, [email protected]
Response.Write “Execution Successful”
%>
EXECUTING STORED PROCEDURE WITH THE COMMAND OBJECT

 The ADO Command object can be used to represent any command that can be
executed against a data source. However, when using the command object with
SQL Server, its greatest functionally is for executing SQL Stored procedure.
 The command object can be used to execute both row returning and non-row
returning stored procedure.
 The command object can be used to retrieve return code and output parameters
from a stored procedure.
Example: 1 (using command object to execute row returning stored procedure)
CREATE PROCEDURE updateHitCount
AS
UPDATE HitCount
Set hits = hits +1
 The above stored procedure updateHitCount simply adds 1 to a column named
Hits in a table named HitCount.
 The above stored procedure can be executed in an Active Server Page by using the
command object.
<! -- #INCLUDE FILE = “adovbs.inc” -->
<%
Set con = server.createobject(“ADODB.connection”)
Con.open “FILE NAME = c:\myDaatLink.UDL;DATABASE = Authors”
Set mycommand = server.createobject(“ADODB.command”)
Mycommand.commandtype = adCmdStoredProc
Mycommand.commandtext = “updateHitCount”
Mycommand.execute
%>
Explanation for the above script
 The above script creates an instance of the command object by using the
create object method of the server object. Next, the command is associated
with an open database connection by using the command object’s
ActiveConnection property. The commandtype property is used to indicate
that the command will be used to execute a SQL stored procedure. The
commandtext property provides the name of the stored procedure in the SQL
database that will be executed. Finally, when the command object’s executed
method is called, the stored procedure is executed and the HitCounttable is
updated.
Example: 2 (using command object to execute non-row returning stored procedure)
 Command object can also be used with non-row returning stored procedure.
To return rows from a standard procedure use the command object with the
recordset object.
 For example, assume that the following SQL stored procedure named authors
exists on the database server. this sample, one-line stored procedure returns all
the rows from authors table.
CREATE PROCEDURE getAuthors AS select*from Authors
 The following script executes this stored procedure and displays a list of all the
authors in the browser
<! -- #INCLUDE FILE =”adovbs.inc”
<%
set con = server. createobject(“ADODB. connection”)
con.open “FILE NAME=c:\myDataLink.UDL;DATABASE=Authors”
set mycommand=server. createobject(“ADODB.command”)
set mycommand.activeconnection = con
mycommand.commandtype = adCmdStoredProc
mycommand.commandtext = “getAuthors”
set RS = mycommand.execute( )
while not RS.eof
Response .write RS (“au_fname”)&”<br>”
RS.movenext
Wend
%>
OUTPUT
Jhonson
Mahesh
Kumar
Using Return Code Parameters With the Command Object
 Using return code parameters, the following arguments must be supplied to the
Create parameter method
o Name – The name of the parameter
o Type-The data type of the parameter. For return code parameter, the type is
always adlnteger
o Direction-Indicates whether the parameter is a return code parameter, input or
output parameter. When used with a return code parameter, the direction
always adparamReturnValue
 Using RETURN statement causes different return codes to be returned from a
stored procedure. These return codes can be used for whether purpose required.
For example, the following stored procedure returns 1 if the author named
‘Senthil’ exists in the Authors table otherwise it returns 0.
CREATE PROCEDURE checkAuthor
AS
IF EXISTS (SELECT au_Iname FROM Authors WHERE au_Iname = ‘Senthil’)
RETURN (1)
ELSE
RETURN (0)
 The command object can be used to capture the return code from a stored
procedure. To do this, an instance of the Parameter Object must be created. It is
explained in the following example
<! -- #INCLUDE FILE = “adovbs,inc”-->
<%
set con = server. createobject(“ADODB.connection”)
con.open “FILE NAME = c:\myDataLink.UDL;DATABASE = Authors”
set mycommand = server. createobject(“ADODB.command”)
set mycommand. Activeconnection = con
mycommand. Commandtype = adCmdStoredProc
mycommand. Commandtext = “checkAuthors”
set myparam = command. Createparameters (“ReturnCode”, adlnteger,
addParamReturnvalue)
mycommand.parameters.append myparam
mycommand.execute ( )
Response .write mycommand (“ReturnCode”)
%>
OUTPUT
1
Using Input Parameter With the Command Object
 The input parameter is created by using the Creates parameter method of
Command object. When used the input parameter, this method accepts the
following arguments
o Name – The Name of the Parameter
o Type – The data type of the parameter. For input parameter, the type is
always adVarCharl or adlnteger or adLongVarChar
o Direction – Indicates that the parameter is a input parameter. When used
with input parameter, the direction always adParamInput
o Size – when creating a parameter with a variable length data type, such as
a VARCHAR, provides the maximum size of the parameter.
 To pass values to a stored procedure an input parameter should be used. For
example, the following stored procedure accepts an input parameter named
@firstLetter that is used to retrieve all the authors whose last name start with a
certain letter.
CREATE PROCEDURE getAuthorsByLastname
(
@ firstletter VARCHAR (1)
)
AS
SELECT*FROM authors
WHERE au_Inmae LIKE @firstletter + ‘%’
o Suppose all the authors whose names start with the letter ‘S’ from Authors
table need to be displayed in an Active Server Page. This can be done
using the following script
<! -- #INCLUDE FILE = “adovbs.inc” -->
<%
set con = server. createobject(“ADODB. Connection”)
con.open “FILE NAME = c:\myDataLink.UDL;DATABASE = Authors”
set mycommand = server. createobject(“ADODB. Command”)
set mycommand. Activeconnection = con
mycommand.commandtype = adCmdStoredProc
mycommand.commandnext = “getAuthorsByLastName”
mycommand.parameters.append mycommand.
Createparameter(“Returncode”,adlnteger, addParamReturnvalue)
mycommand.parameters.append mycommand. Createparameter
(“firstletter”,adVarChar, addParamInput, 1)
mycommand.parameters(“firstletter”)= “S”
set RS = mycommnd. Execute ( )
while not RS.eof
Response. Write RS (“au_Iname”)&”<br>”
RS.movenext
Wend
%>
OUTPUT
Senthil
Sachin
Sourav
Stalin
Using Output Parameter With the Command Object
 An output parameter is created in a similar fashion to an input parameter
with CreateParameter method. The arguments that are used with this
method is as follows
o Name – The Name of the Parameter. The name is used when
passing a value to the input parameter
o Type –The data type of the parameter.
o Direction – Indicates that the parameter is a output parameter.
When used with Output parameter, the direction always
adParamOutput
o Size – when creating a parameter with a variable the maximum
size of the parameter.
 When retrieving a single record from a database table, or calculating a
single value, a stored procedure, which returns an output parameter should
be used. Using an output parameter is always more efficient than using a
Recordset Object to retrieve single row from a database table.
 Foe example, suppose that first name needs to be retrieved from a table
when only the person’s id is supplied. It might be tempting to open
Recordset with SQL query to find the email address. This should be
avoided, but instead, the following stored procedure could e used
CREATE PROCEDURE getauid
(
@au_fname VARCHAR(30)
@au_id VARCHAR(10) OUTPUT
)
AS SELECT @au_id = au_id FROM Authors WHERE au_fname =
@au_fname
 To use the above stored procedure in an Active Server Page, the value of
the output parameter must be retrieved into an instance of the ADO
Parameter Object.
<! -- #INCLUDE FILE = “adovbs.inc” -->
<%
Set con = server .createobject(“ADODB.CONNECTION”)
Con.open “FILE NAME =c:\myDataLink.UDL;DATABASE =
Authors”
set mycommand = server.createobject(“ADODB.command”)
set mycommand.activeconnection = con
mycommand.commandtype = adCmdStoredProc
mycommand.commandtext = “getauid”
mycommand.parameters.append mycommand.
Createparameter(“ReturnCode”, adlnteger, addParamReturnvalue)
mycommand.parameters.append
mycommand.createparameter(“au_id”,adVarChar, adParamInput,20)
mycommand.parameters(“au_id”) = “123_45_678”
mycommand.parameters.append mycommand.createparameter
(“au_fname”,adVarChar, addParamInput,100)
mycommand.execute
Response. Write mycommand(“au_fname”)
%>
OUTPUT
Abdul Kalam
(because the Abdul Kalam id is 123_45_678)
RETRIVING PARAMETER INFORMATION
 A stored procedure might be needed but the parameter but the parameters built
into the procedure may be unknown i.e. the data type of the parameter and their
size are unknown this information needs to be determined by referring to the
procedure itself.
 To retrieve information about the parameters used in a stored procedure we can
use the following scripts.
<! -- #INCLUDE FILE = “adovbs.inc”-->
<%
set con = server. createobject(“ADODB.connection”)
con.open “FILE NAME = c:\myDataLink.UDL;DATABASE = Authors”
set mycommand = server.createobject(“ADODB.command”)
set mycommand.activeconnection = con
mycommand.commandtype = adCmdStoredProc
mycommand.commandtext = “checkgetAuthors”
mycommand.parameters.refresh
%>
<HTML>
<HEAD>
<TITLE>Parameter Information </TITLE>
</HEAD>
<BODY>
<TABLE BORDER = 1>
<CAPTION>Parameter Information</CAPTION>
<TR>
<TH> Parameter Name </TH>
<TH> Datatype </TH>
<TH>Direction </TH>
<TR>
<% For Each Thing in mycommand.parameters %>
<TR>
<TD> <% = thing.name %> </TD>
<TD> <% = thing.type %> </TD>
<TD> <% = thing.direction %> </TD>
<TD> <% = thing.size %> </TD>
</TR>
<%
next
con.close %>
</TABLE>
</BODY>
</HTML>
 The above script will displays all the parameter information for the procedure
named checkgetAuthors. The name, data type, direction and size for each
parameter is displayed in a table. (The Direction indicates whether the parameter
is an input parameter, output parameter, or return status value) To display
information about another stored procedure, simply substitute the procedure’s
name for checkgetAuthors.
 The important statement in this example is Mycommand.Parameters.Refresh.
 When this statement is executed, information about the stored procedure’s
parameter is retrieved from the database.
---------------------XXXXXXXXXXXXXXXXXXX----------------------------

You might also like