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. In short, write SQL queries in a specific format in the SQL server and call them from your application, instead of writing queries inside your program code.
You can write Stored Procedures in the following possible ways:
CREATE PROCEDURE sp_councillors AS
BEGIN
SELECT au_fname,au_lname,au_party,au_elected
FROM tblCouncillors
WHERE au_county = 'CUMBRIA'
END
GO
The above code would be entered in SQL Server Enterprise Manager
To pass parameters to the stored procedure, prefix the field name with a @ symbol:
CREATE PROCEDURE sp_councillors
@political_party varchar(50)
AS
BEGIN
SELECT au_fname,au_lname,au_party,au_elected
FROM tblCouncillors
WHERE au_party = @political_party
END
GO
In the above example, @political_party is the input parameter and the values will be sent by your ASP or VB code.
CREATE PROCEDURE sp_total_councillors
@political_party varchar(50),
@count_councillors int OUTPUT
AS
BEGIN
SELECT @count_councillors = Count(*)
FROM tblCouncillors
WHERE au_party = @political_party
END
GO
Here the total no of councillors who are in the specified political party will be counted and sent through the output parameter. You can see the keyword OUTPUT to differentiate the output parameter from the input parameter.
The following code snippet would be typed into an ASP page:
<%
!--#INCLUDE VIRTUAL="/include/adovbs.inc"-->
Dim objConn, objCmd, objParam
set objConn = Server.CreateObject("ADODB.Connection")
objConn.Open "DSN=testdb;uid=test;pwd=test"
Set objCmd = Server.CreateObject("ADODB.Command")
objCmd.CommandText = "sp_total_councillors"
objCmd.CommandType = adCmdStoredProc
objcmd.ActiveConnection = objConn
objCmd.Parameters.Append objCmd.CreateParameter ("@political_party",adVarChar,adParamInput,50,"LABOUR")
objCmd.Parameters.Append objCmd.CreateParameter ("@count_councillors",adInteger,adParamOutput,4)
ObjCmd.Execute
%>
<HTML>
<BODY>
No of Councillors who are members of the LABOUR Party: <%= objCmd.Parameters.("@count_councillors")%>
</BODY>
</HTML>
In the above example we are specifying an Input AND an Output parameter. Note the input parameter has an extra value - "LABOUR", which is used to pass the selection data to SQL.