SQL StoredProcBasics
SQL StoredProcBasics
A note – the below is my humble opinion – with testing – If you use my ideas
please test them and if you have problems or learn more let me know.
* Stored Procedures are precompiled Transact-SQL statements stored in a SQL Server database.
* Stored Procedures are one of the most powerful pieces of programming you will ever see. When you
start out, you will see them as a way to return a record set, or do some small update on your data. As
you learn more about SPs you will understand why there are entire books written on the subject. SQL
Server compiles the Proc so that when you run it, it runs as fast as possible. Once you write a couple of
complicated SPs, you will be convinced. This paper only covers the tip of the Stored Procedure iceberg.
* I will refer to Stored Procedures in this document as SP and Proc - get use to it.
Stored Procedure Name Parameter Check Syntax Run Button Database running against Result set
Figure -2-2
Running a
procedure on
Query Ana-
lyzer
* If you notice in Figure 2-2, it shows “(3 row(s) affected)”. If you don’t set “set nocount on” in a SP,
when you run the SP in the Query Analyzer, you will get back a message “X rows affected”. By set-
ting nocount on, it stops SQL Server from doing some work, that you don’t care about. This will cause
the SP to run just a little faster.
* You need to learn about sp_Help and other system stored procedures.
Works with or without the single quotes. Figure 2-3
cnnTemp.Open
'Open Connection
Set Cmd1 = New ADODB.Command
Cmd1.ActiveConnection = cnnTemp
'---
With Cmd1
.CommandText = "z_sp_SimpleReadTable"
.CommandType = adCmdStoredProc .Parameters.Refresh
.Parameters("@vcCompanyName").Value = "bus"
End With
' rs1.MoveNext
'Wend
'The following lines shows all the records and all fields fro the above recordset
Debug.Print rs1.GetString(adClipString, , ";")
rs1.Close
Finish_Up:
ex_SP_ReadRecords = True
ProcedureDone:
On Error Resume Next
rs1.Close
Set Cmd1 = Nothing
Set rs1 = Nothing
Exit Function
HandleError:
Debug.Print Err.Number, Err.Description
Resume ProcedureDone
End Function
'----
Note: If you run this procedure 'Open Command Object
from the query analyzer, you will Set Cmd1 = New ADODB.Command
need to put in a false parameter Cmd1.ActiveConnection = cnnTemp
for the output parameter, and
probably put a print statement in- '---With Cmd1
side the proc to show the output .CommandText = "z_sp_In_Out_Parameters_Simple"
parameter in the query analyzer. .CommandType = adCmdStoredProc
.Parameters.Refresh
.Parameters("@vcCo_IdT").Value = 266
.Execute , lngRecordsAffected, adExecuteNoRecords
End With
z_sp_In_Out_Parameters_Simple '266', ''
Debug.Print Cmd1.Parameters("@vcOutPut1").Value
ProcedureDone:
Exit Function
HandleError:
Delete data
* Ok, so I made it a little more difficult
than it had to be. To delete records
from a table you can just have one line
in the procedure:
delete tbl_City where Figure 4-2 ADO to Run the Above Delete Action
City_Id = @intId Public Function ex_SP_QueryDelete() As Boolean
You can pass an input pa- '>>> Stored Procedure & ADO are about the same Speed <<<
rameter '----
' Purpose: Use a stored Procedure to run the delete query
Create Procedure abc ' Required Elements: Stored Procedure --> z_sp_qry_DeleteRecords_PassWhere
@intId as Int ' Example: ex_SP_QueryDelete()
as '----
' Parameters:
delete tbl_City where City_Id '----
= @intId ' Returns:
return '---
Dim Cmd1 As ADODB.Command
Dim strWhereStatement As String
The Easy '----
Cmd1.Execute
* In figure 4-2 we run the ex_SP_QueryDelete = Cmd1.Parameters("RETURN_VALUE").Value
Proc with ADO Code. Debug.Print "Records Deleted: --> " & Cmd1.Parameters("@inRecCount").Va lue
Figure 4-4
Update the data in one table with data from another table.
Make a Table Figure 4-5 Make a Table with Data from Another Recordset
* In figure 4-5 we are
creating a table with
data from another
recordset. When we
get finished data will
be in the table.
> We delete
table
tmpCity if it
exist.
Section A
Section B
* If you are like me and use the “IIf” statement in Access queries, you are going to want to know what
you can replace it with in SQL Server. There are no replacements in Views, however in SPS you can
use the case statement. In figure 5-1 we have a SP that looks at the field Mail_St which is a 2 character
field for the state. If it = KS we substitute Kansas, if MO we use Missouri, otherwise we use the actual
value in the field Mail_St. You can see how it comes out in figure 5-2.
Replace('aabbccdd', 'bb', 'xx') Replace all 'bb' in the original string with 'xx'
CharIndex(“XYZ”, “Y”) Find a position of a particular string select CHARINDEX('Joe', 'Smith, Joe') returns 8
Substring("Test This",6, 20) In SQL Server you have to put the length, however in Access you are not required to
Substring(Expression, Start, have the length. The secret in SQL Server is to put the maximum length it could ever be
Length) (if it’s greater than string length, that’s not a problem).
Ltrim(x) Trim the spaces off the Left of a string Ltrim(“ SQL”) returns “SQL”
Rtrim(x) Trim the spaces off the Right of a string Rtrim(“SQL ”) returns “SQL”
Char(x) Returns a character associated with the specified character code. Chr(65) will return A
q, qq Quarter
m, mm Month
y, dy Day of Year
d, dd Day
ww, wk Week
dw WeekDay
hh Hour
mi, n Minute
s, ss Second
ms millisecond
yy, yyyy Year
int Integer (whole number) data from -2^31 (-2,147,483,648) through 2^31 - 1 (2,147,483,647). About 2 bil-
lion minus to 2 billion plus
smallint Integer data from 2^15 (-32,768) through 2^15 - 1 (32,767).
decimal Fixed precision and scale numeric data from -10^38 -1 through 10^38 -1.
real Floating precision number data from -3.40E + 38 through 3.40E + 38.
datetime Date and time data from January 1, 1753, to December 31, 9999, with an accuracy of three-hundredths of
a second, or 3.33 milliseconds.
small- Date and time data from January 1, 1900, through June 6, 2079, with an accuracy of one minute.
datetime
timestamp A database-wide unique number. A table can have only one timestamp column. The value in the time-
stamp column is updated every time a row containing a timestamp column is inserted or updated.
uniqueiden- A globally unique identifier (GUID).
tifier
char Fixed-length non-Unicode character data with a maximum length of 8,000 characters.