Tải bản đầy đủ (.pdf) (50 trang)

Tài liệu Programming Microsoft SQL Server 2000 with Microsoft Visual Basic .Net - P3 doc

Bạn đang xem bản rút gọn của tài liệu. Xem và tải ngay bản đầy đủ của tài liệu tại đây (618.37 KB, 50 trang )

DROP VIEW vewEmailContacts
GO

--Create view to select all columns for
--all rows from the EmailContacts table.
CREATE VIEW vewEmailContacts
AS
SELECT *
FROM EmailContacts
GO

--Select all columns for all rows from
--the vewEmailContacts view.
SELECT *
FROM vewEmailContacts

Cont ra sting Un e n cr ypt ed and Encrypt ed View s
Wit h m inor ext ensions, the preceding sam ple can serve as a t em plat e for t he
creat ion of any view. The following script illust rat es one of t hese ext ensions. I t
creat es a view in t he Chapt er04 dat abase t hat has t he Shippers t able in the
Nort hwind dat abase as it s base t able. While t he row source for a view can reside
in anot her dat abase, t he CREATE VI EW st at em ent can creat e a view only in t he
current dat abase. Sim ilarly, t he DROP VI EW st at em ent can rem ove a view only
from t he current dat abase.
An easy way t o r eference a row source fr om anot her SQL Server dat abase is t o
use a t hree- part nam e. The first part refers t o t he alt ernat e dat abase nam e,
Nort hwind in t his case. The second part designat es t he owner of t he obj ect
prov iding t he row source. When t he row source owner is t he default dbo user,
you can om it it s explicit designat ion ( as in t he follow ing scr ipt ). The t hird nam e
part denotes t he nam e of t he dat abase obj ect providing t he row source for a
view . Figure 4- 1 shows t he resu lt set from t he SELECT st at em ent based on t he


vewShippers view. Not ice t hat it m at ches t he values in t he Nort hwind..Shippers
table, which is the source for t he v ewShippers view.
Not ice t hat unlike t he first code sam ple, t his one doesn’t include a specific
reference t o t he Chapt er04 database. That ’s because Query Analyzer w ill cont inue
to use Chapter04 unt il y ou specify a different dat abase wit h a new USE
st at em ent .
--CreatevewShippers
--Search for, and remove if found, the
--vewShippers view in the Chapter04 database.
IF EXISTS (SELECT TABLE_NAME FROM INFORMATION_SCHEMA.VIEWS
WHERE TABLE_NAME = ’vewShippers’)
DROP VIEW vewShippers
GO

--Create a new version of the vewShippers
--view in the Chapter04 database from the
--Shippers table in the Northwind database.
CREATE VIEW vewShippers
AS
SELECT *
FROM Northwind..Shippers
GO

--Select all rows and columns from the
--vewShippers view in Chapter04.
SELECT * FROM vewShippers
Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.

Figu re 4 - 1 . Th e resu lt set from a v ie w base d on t he Ship pe rs t able in t he
N or t hw in d da t ab ase .


The ENCRYPTI ON at t r ibut e isn’t set by default . Set t ing encrypt ion doesn’t change
the result set from a SELECT st at em ent. I nst ead, it encodes t he T- SQL for a
view ’s definit ion. You can verify t his by t r ying t o disp lay t he script for a view. The
VI EW_DEFI NI TI ON colum n for t he I NFORMATI ON_SCHEMA.VI EWS view ret urns
the script for a v iew on each of it s r ow s.
The follow ing scr ipt dem onst rat es t he sy ntax for invoking t he ENCRYPTI ON
at t ribut e. The scr ipt also dem onst rat es t he sy nt ax for ret urning t he script t hat
defines a view . This script includes all com m ent s as well as t he operat ional T- SQL
st at em ent s for cr eat ing t he v iew; t hese st at em ents include the CREATE VI EW
st at em ent for generat ing a new v iew and t he SELECT st at em ent for defining a
view ’s result set . I n t his case, t he SELECT st at em ent is ident ical t o t he one in t he
preceding view . How ever, t he CREATE VI EW st at em ent includes t he WI TH
ENCRYPTI ON clause t hat encodes t he T- SQL for t he view. After cr eat ing t he view,
the script perfor m s a sim ple SELECT query t o v erify t he cont ent s of t he view ’s
result set . Th e final port ion of t he script creat es anot her result set w ith t he
definit ion for each user- defined view in t he current dat abase, which is Chapt er04
in t he sam ple. Om it t ing all row s beginning wit h “sys” for t heir TABLE_NAME
colum n value in t he I NFORMATI ON_SCHEMA.VI EWS view excludes all syst em
view s from the final result set .
--CreatevewShippersEncrypted
--Search for, and remove if found, the
--vewShippersEncrypted view in the Chapter04 database.
IF EXISTS (SELECT TABLE_NAME FROM INFORMATION_SCHEMA.VIEWS
WHERE TABLE_NAME = ’vewShippersEncrypted’)
DROP VIEW vewShippersEncrypted
GO

--Create a new version of the vewShippersEncrypted
--view in the Chapter04 database from the

--Shippers table in the Northwind database.
CREATE VIEW vewShippersEncrypted
WITH ENCRYPTION
AS
SELECT *
FROM Northwind..Shippers
GO

--Select all rows and columns from the
--vewShippersEncrypted view in Chapter04.
SELECT * FROM vewShippersEncrypted

--List user-defined view names in Chapter04 database
--along with their scripts.
SELECT TABLE_NAME, VIEW_DEFINITION
FROM INFORMATION_SCHEMA.VIEWS
WHERE LEFT(TABLE_NAME,3) <> ’sys’

Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
Figure 4- 2 sh ow s an excerpt from t he result set s for t he pr eceding script s. This
excerpt is from t he Result s pane of Query Analy zer wit h a Result s To Grids
set ting. The t op result set sh ows t he sam e t hree rows as in Figure 4-1. This
confirm s that encrypt ing a view doesn ’t alt er t he resu lt from it s SELECT
st at em ent . The second result set in Figure 4- 2 displays t he nam es of t he t hree
view s cr eat ed t o t his point in t he chapt er. Next t o each view nam e is t he
beginning of t he script for t he view. Because t he script s st art w it h com m ent s, t he
VI EW_DEFI NI TI ON colum n values st art wit h t hese com m ents. Wit h a Result s To
Text set t ing for t he Result s pane, you can exam ine t he w hole script for each view
except vewSh ippersEncr ypted. The WI TH ENCRYPTI ON clause in t he CREATE
VI EW st at em ent for t his view secures it s script so that t he VI EW_DEFI NI TI ON

colum n of t he I NFORMATI ON_SCHEMA.VI EWS view cannot expose t he T- SQL t hat
generat es t he view .
Figu re 4 - 2 . An e xce r pt show ing th e resu lt set fr om a n e ncryp t ed view a s
w e ll as t h e VI EW _ D EFI N I TI ON colum n va lu es from t h e
I N FORM ATI ON _ SCH EM A.V I EW S vie w for t h re e view s in a dat abase .

Sor t ing a n d Grouping W it hin a Vie w
The SELECT st at em ent t hat def ines a view has generally t he sam e sy nt ax as t hat
wit hin a st and- alone script. For exam ple, gr ouping rows t o aggr egat e a colum n
value works t he sam e in both st and- alone script s and t hose inside view s.
Sim ilarly, t he I N keyword in a WHERE clause works the sam e as well.
I n cont rast , t he ORDER BY clause in a SELECT st at em ent requires slight ly
different sy nt ax inside a view t han it does out side a view . I n part icular, ORDER
BY inside a v iew requires the TOP predicat e aft er t he SELECT keyword. The TOP
predicat e, in t urn, r equires an argum ent t o designat e how m any records t o
ret ur n. I f you want all t he rows from a source, follow TOP wit h 100 PERCENT. You
can designat e any ot her percent age as w ell as a num ber for any num ber of rows.
Trailing TOP w it h t he num ber 10 w it hout t he PERCENT keyword ret urns the first
10 rows in t he result set . When you use an ORDER BY clause, t hose row s will be
the highest or lowest colum n values on a sort dim ension depending on the sort
order. The sy nt ax for designat ing a sort order in an ORDER BY clause is the sam e
in a SELECT st at em ent in or out of a view .
The follow ing scr ipt shows the cr eat ion and ret urn of values from a view t hat
groups and sort s colum n values. The SELECT st at em ent for t he v iew also includes
a crit er ion t hat filters exclusively for countries beginning wit h t he let t er B or C.
Chapt er 3 included a sim ilar st and-alone script for count ing t he num ber of
cust om ers by cit y wit hin count r y. Th e SELECT st at em ent in t he follow ing scr ipt is
dist inct because of it s use of t he TOP predicat e. While t he TOP predicat e will w ork
in a st and-alone script , it isn’t necessary.
--CreatevewCustomersInCountryCity

--Search for, and remove if found, the
--vewCustomersInCountryCity view in the Chapter04 database.
IF EXISTS (SELECT TABLE_NAME FROM INFORMATION_SCHEMA.VIEWS
WHERE TABLE_NAME = ’vewCustomersInCountryCity’)
Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
DROP VIEW vewCustomersInCountryCity
GO

--Create a new version of the vewCustomersInCountryCity
--view in the Chapter04 database.
--To use ORDER BY clause in view you need TOP predicate
--with modifier of 100 PERCENT.
CREATE VIEW vewCustomersInCountryCity
AS
SELECT TOP 100 PERCENT Country, City,
Count(CustomerID) ’# of Customers’
FROM Northwind..Customers
WHERE LEFT(Country,1) IN (‘B’,’C’)
GROUP BY Country, City
ORDER BY Country, City
GO

--Select all rows and columns from the
--vewCustomersInCountryCity view in Chapter04.
SELECT * FROM vewCustomersInCountryCity


View s for Rem ot e a nd H et erogeneous Sources
I t is oft en necessary t o view dat a r esiding on anot her SQL Server inst ance or
even in anot her t ype of dat abase form at . T- SQL provides sever al appr oaches t o

sat isfying t hese kinds of requirem ent s. The OPENROWSET funct ion is a flex ible
approach because it can accom m odat e ad hoc queries as well as t hose perform ed
on a regular basis. As m ent ioned prev iously, Books Online recom m ends t hat y ou
use link ed ser vers when it is necessary t o query a rem ot e or het er ogeneous
source on a regular basis. Howev er, you can invoke t he OPENROWSET funct ion
for a userid t hat doesn’t have m em bership in t he sysadm in or set upadm in fixed
server roles. The OPENROWSET funct ion depends only on t he perm issions for t he
user id passed t o t he ot her dat a source. This sect ion present s a ser ies of
OPENROWSET sam ples designed t o help you underst and rem ot e dat a access.
Creat ing a View for Anot her SQL Ser ver I n st a nce
One t ypical requirem ent is t o view a SQL Serv er row source, such as a t able, on
anot her server. You can use t he OPENROWSET funct ion to perform t his task , wit h
argum ent s t hat sp ecify a prov ider, ot her elem ents of a connect ion st ring, and a
SELECT st at em ent . The OPENROWSET funct ion can serve as an argum ent for t he
FROM clause of a SELECT st at em ent . This out er SELECT st at em ent , in t urn, m ust
reside in a CREATE VI EW st at em ent w hen your goal is t o creat e a v iew in t he
current dat abase t hat exposes a row source in anot her dat abase.
When the inner SELECT st at em ent — t he one in t he call t o t he OPENROWSET
funct ion— point s at anot her SQL Server inst ance, t he provider for t he funct ion
should be SQLOLEDB. Next you can denot e t he rem aining elem ents of t he
connect ion st ring for t he ot her server in t he follow ing order: t he ser ver inst ance
nam e, a SQL Serv er login for t he server , and a passw ord for t he login. Follow t he
prov ider nam e by a com m a, but use a sem icolon for a delim it er aft er t he server
nam e and login nam e. A com m a separat es t he passw ord from t he SELECT
st at em ent .
The follow ing scr ipt cr eat es a view on one SQL Server running SQL Server 2000
that point s at a t able on t he cabxli ser ver running t he MSDE version com pat ible
wit h SQL Server 7. You need t w o inst ances of SQL Server t o evaluat e t his scr ipt ,
Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
but you can nam e t he inst ances anyt hing you want. Just ch ange t he references to

cabxli to t he nam e of a SQL Server inst ance t o which you can connect . By t he
way, t he table is t he aut hors table in t he pubs dat abase; MSDE doesn’t rout inely
inst all w it h t he pubs dat abase. Because cabx li is an int er nal t est serv er running
Windows 98, t he serv er is available w it h sa and an em pt y password. Product ion
servers should always have a password for t he sa login if you aren’t forcing
Windows aut hent icat ion. The SELECT st at em ent refer ences t he aut hors t able in
the pubs dat abase on t he cabxli server. The ORDER BY clause along wit h t he TOP
predicat e sort s t he result set by aut hor first nam e w it hin aut hor last nam e.
The out er SELECT st at em ent t akes t he OPENROWSET funct ion as t he argum ent
for it s FROM clause. The SELECT list for t he outer SELECT st at em ent list s t he
aut hors by first nam e, last nam e, and phone num ber, in t hat order.
--CreatevewAuthorsSortedOnCabxli
--Search for, and remove if found, the
--vewAuthorsSortedOnCabxli view in the Chapter04 database.
IF EXISTS (SELECT TABLE_NAME FROM INFORMATION_SCHEMA.VIEWS
WHERE TABLE_NAME = ’vewAuthorsSortedOnCabxli’)
DROP VIEW vewAuthorsSortedOnCabxli
GO

--Create a new version of the vewAuthorsSortedOnCabxli
--view in the Chapter04 database from the
--Shippers table in the Northwind database.
CREATE VIEW vewAuthorsSortedOnCabxli
AS
SELECT au_fname, au_lname, phone
FROM OPENROWSET(‘SQLOLEDB’,’cabxli’;’sa’;’’,
’SELECT TOP 100 PERCENT * FROM pubs..authors ORDER BY au_lname, a
u_fname’)
GO


--Select all rows and columns from the
--vewAuthorsSortedOnCabxli view in Chapter04.
SELECT * FROM vewAuthorsSortedOnCabxli
GO

Creat ing a View for an Acce ss Dat aba se
I t isn’t uncom m on t o need t o upgrade Access applicat ions for t he use of an
Access dat abase via a SQL Server solut ion. While you can perform a full-scale
upsizing, it is possible t hat t he OPENROWSET funct ion can dram at ically reduce
the effort of w orking w it h Access dat a from SQL Server. That ’s because t he
funct ion perm it s a SQL Server solut ion t o view Access dat a wit hout t he need of
transport ing t he dat a from Access t o SQL Server. Therefore, you save t he
conversion effort . I n addit ion, your client s avoid the disrupt ion t hat could arise if
their fam iliar Access solut ion were unavailable because you replaced it wit h a SQL
Server applicat ion. At t he sam e t im e, new applicat ions can expose dat a from t he
Access dat abase. So long as you don’t expect to exper ience bot t leneck s relat ed t o
the capacit y of t he Access dat abase, this approach bears considerat ion. I n any
event , the approach support s t he easy availabilit y of Access dat a from SQL
Server views.
You can use an OPENROWSET funct ion t o connect wit h an Access dat abase m uch
like you use t he funct ion t o connect w it h a SQL Server dat abase on anot her SQL
Server inst ance. The OPENROWSET funct ion is t he argum ent for t he FROM clause
of a SELECT st at em ent . When connect ing t o an Access dat abase, you m ust
specify t he Jet dat a provider followed by t he pat h t o t he Access database file, a
login nam e, and a passw ord. Th e OPENROWSET funct ion also has it s ow n SELECT
Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
st at em ent t hat specifies t he row source in t he Access dat abase as w ell as any
special set t ings, such as a WHERE clause.
The follow ing scr ipt dem onst rat es a connect ion to an Access dat abase file on the
current com put er. The pat h points t o t he default inst allat ion of t he Nor t hw ind

sam ple dat abase for Access 2002. The connect ion st ring specifies a login by t he
adm in user wit h an em pt y password. This is norm al for an unsecured Access
dat abase file, such as t he Access Nort hw ind sam ple. Th e SELECT st at em ent inside
the OPENROWSET funct ion call designat es t he retur n of all rows wit h a Count ry
colum n value of USA. When designat ing a st ring in t his inst ance, t he norm al
synt ax is t o enclose t he st ring argum ent , USA, wit h a pair of single quot at ion
m arks. How ever, w it hin the OPENROWSET funct ion, single quot at ion m arks are
alr eady used around the SELECT st at em ent , so it ’s necessary t o use t wo single
quot at ion m arks on each side of USA. I n t he following script , t he out er SELECT
st at em ent disp lays all t he colum ns from the inner SELECT st at em ent .
--CreatevewUSACustomersFromAccess
--Search for, and remove if found, the
--vewUSACustomersFromAccess view in the Chapter04 database.
IF EXISTS (SELECT TABLE_NAME FROM INFORMATION_SCHEMA.VIEWS
WHERE TABLE_NAME = ’vewUSACustomersFromAccess’)
DROP VIEW vewUSACustomersFromAccess
GO

--Create a new version of the vewUSACustomersFromAccess
--view in the Chapter04 database from the Customers table
--in the Access Northwind database. (You should install the
--Northwind sample if it isn’t already installed. Also, you
--may need to change the path to Northwind.)
CREATE VIEW vewUSACustomersFromAccess
AS
SELECT *
FROM OPENROWSET(
’Microsoft.Jet.OLEDB.4.0’,
’c:\Program Files\Microsoft Office\Office10\Samples\Northwind.mdb
’;

’admin’;’’,
’SELECT * FROM Customers WHERE Country=‘‘USA’’’)
GO

--Select all rows and columns from the
--vewUSACustomersFromAccess view in Chapter04.
SELECT * FROM vewUSACustomersFromAccess
GO

Creat ing a View for an OD BC Row Sou r ce
View ing an ODBC dat a source m ay be t he ult im at e in flex ibilit y because ODBC
drivers are available for so m any different t ypes of dat abases. I n addit ion, t he
MSDASQL provider, which is inst alled w it h Micr osoft Dat a Access Com ponent s,
offers a st andard int erface t o ODBC dat a sources. The OPENROWSET funct ion
through it s SELECT st at em ent let s your applicat ions ch oose a specific row source
wit hin a dat a source or even filt er a r ow source t o der ive a new cust om source for
an applicat ion.
Using t he OPENROWSET funct ion t o connect with a row source in an ODBC dat a
source bears a st rong r esem blance t o using t he funct ion t o connect wit h SQL
Server and Jet r ow sources. The m ain differences are in the connect ion st ring
specificat ions. Fir st y ou m ust designat e t he MSDASQL provider inst ead of t he
Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
SQLOLEDB or Jet provider. Second you specify connect ion st ring elem ent s t hat
are appropr iat e for t he dat a source t o which y ou want t o connect .
The follow ing scr ipt shows the sy nt ax for an applicat ion of t he OPENROWSET
funct ion w it h t he MSDASQL prov ider for an ODBC dat a source. I n fact , t he sam ple
connect s t o a SQL Server dat a source wit h t he ODBC dr iver, but t he general
synt ax issues are t he sam e as for any dat a source. This sam ple requir es t wo
inst ances of SQL Serv er . For exam ple, t he connect ion st r ing elem ent s point t o t he
cab2000 server running a SQL Serv er dat abase. You can replace t he reference t o

cab2000 wit h t he nam e of any ot her inst ance of SQL Serv er on y our net work. The
user id and passw ord are, respect iv ely, sa and password. The inner SELECT
st at em ent for t he OPENROWSET funct ion ch ooses all t he row s from t he Orders
table in t he Nort hwind dat abase whose OrderDat e is in 1998. A WHERE clause
and a DATEPART funct ion part icipat e in t he designat ion of an appropriat e cr it erion
for t he SELECT st at em ent . The outer SELECT st at em ent ret urns all colum ns from
the Orders t able.
--Createvew1998OrdersOnCab2000
--Search for, and remove if found, the
--vew1998OrdersOnCab2000 view in the Chapter04 database.
IF EXISTS (SELECT TABLE_NAME FROM INFORMATION_SCHEMA.VIEWS
WHERE TABLE_NAME = ’vew1998OrdersOnCab2000’)
DROP VIEW vew1998OrdersOnCab2000
GO

--Create a new version of the vew1998OrdersOnCab2000
--view in the Chapter04 database from the Orders table
--in the Northwind database on the Cab2000 server.
CREATE VIEW vew1998OrdersOnCab2000
AS
SELECT *
FROM OPENROWSET(‘MSDASQL’,
’DRIVER={SQL Server};SERVER=cab2000;UID=sa;PWD=password’,
’SELECT *
FROM Northwind..Orders
WHERE DATEPART(yyyy, OrderDate) = 1998’)
GO

--Select all rows and columns from the
--vew1998OrdersOnCab2000 view in Chapter04.

SELECT * FROM vew1998OrdersOnCab2000

Joining Row Sour ces for a View
The value of being able t o pr ocess rem ot e and het erogeneous dat a sources
m ult iplies when you can j oin t wo row sources from different serv ers or different
dat abases. There are at least t wo approaches t o t his t ask. The first one is t o
creat e a SELECT st at em ent t hat cont ains a JOI N operat or. I n t his approach, each
side of t he j oin has it s own explicit OPENROWSET funct ion. The ot her approach is
to cr eat e t w o new views, each based on it s own OPENROWSET funct ion. Then y ou
can cr eat e a new, t hird, view t hat j oins t he t wo views. Eit her appr oach em pow ers
an applicat ion t o process concurrent ly row sour ces from differ ent dat abase
servers in different dat abase form at s!
The follow ing scr ipt shows the sy nt ax for t he first approach. Like several of t he
previous OPENROWSET funct ion sam ples, t his one r equires t wo inst ances of SQL
Server. The scr ipt j oins rows fr om t he Or ders t able in a SQL Server dat abase w it h
rows from t he Cust om ers t able in an Access dat abase file. The OPENROWSET
funct ion declarat ions follow t he synt ax of prev ious sam ples t hat used t he
funct ions separately as t he source for a view . This scr ipt sam ple j oins t he
Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
Cust om ers r ows wit h the Or ders rows based on t heir Cust om erI D colum n values.
An advant age of nest ing t he t wo OPENROWSET funct ions as t he argum ent for t he
FROM clause of t he out er SELECT st at em ent is t hat your applicat ion doesn’t
require separat e v iews for each row source obj ect t hat get s j oined. This saves
your applicat ion from opening t he views.
--CreatevewAccessCustomersCab2000Orders
--Search for, and remove if found, the
--vewAccessCustomersCab2000Orders view in the Chapter04 database.
IF EXISTS (SELECT TABLE_NAME FROM INFORMATION_SCHEMA.VIEWS
WHERE TABLE_NAME = ’vewAccessCustomersCab2000Orders’)
DROP VIEW vewAccessCustomersCab2000Orders

GO

--Create the vewAccessCustomersCab2000Orders view
--in the Chapter04 database from the
--OPENROWSET of CustomersFromAccess and
--OPENROWSET of 1998OrdersOnCab2000.
CREATE VIEW vewAccessCustomersCab2000Orders
AS
SELECT TOP 100 PERCENT c.CompanyName, c.ContactName, c.Phone,
o.OrderID, LEFT(o.OrderDate, 11) ’Order Date’
FROM OPENROWSET(‘Microsoft.Jet.OLEDB.4.0’,
’C:\Program Files\Microsoft Office\Office10\Samples\Northwind.mdb
’;
’admin’;’’,
’SELECT *
FROM Customers
WHERE Country=‘‘USA’’’) AS c JOIN
OPENROWSET(‘MSDASQL’,
’DRIVER={SQL Server};SERVER=cab2000;UID=sa;PWD=password’,
’SELECT *
FROM Northwind.dbo.Orders
WHERE DATEPART(yyyy, OrderDate) = 1998’)
AS o
ON c.CustomerID = o.CustomerID
ORDER BY c.CompanyName, o.OrderID
GO

--Select all rows and columns from the
--vewAccessCustomersCab2000Orders view in Chapter04.
SELECT * FROM vewAccessCustomersCab2000Orders


The next script shows t he sy nt ax for t he alt ernat ive approach t o j oining t wo
het er ogeneous dat a sources. Again, y ou need t wo SQL Server inst ances t o run
the sam ple. Th is alt ernat ive j oins t wo pr eviously creat ed v iews. I n this inst ance,
each view is from a prior sam ple in t his chapt er. I n addit ion, t he t wo views
corr espond t o t he SELECT st at em ent s for each of t he nest ed OPENROWSET
funct ions in the prior sam ple. Therefore, t he result is ident ical for t he next scr ipt
and t he prior scr ipt . Howev er, t he code for t he next scr ipt is dram at ically sim pler.
By segm ent ing t he t wo OPENROWSET funct ions int o separat e views, t he second
approach m ak es it easier t o debug t he synt ax . On t he ot her hand, wit h t his
approach your applicat ion requires the addit ional overhead of m anaging t wo
separat e views. This includes cr eat ing, m aint aining, and opening t he v iew s.
--Createvew2JoinedViews
--Search for, and remove if found, the
--vew2JoinedViews view in the Chapter04 database.
IF EXISTS (SELECT TABLE_NAME FROM INFORMATION_SCHEMA.VIEWS
WHERE TABLE_NAME = ’vew2JoinedViews’)
DROP VIEW vew2JoinedViews
GO
Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.

--Create a new version of the vew2JoinedViews
--view in the Chapter04 database from
--two other previously existing views.
CREATE VIEW vew2JoinedViews
AS
Select TOP 100 PERCENT c.CompanyName, c.ContactName, c.Phone,
o.OrderID, LEFT(o.OrderDate, 11) ’Order Date’
FROM vewUSACustomersFromAccess c JOIN vew1998OrdersOnCab2000 o
ON (c.CustomerID = o.CustomerID)

ORDER BY c.CompanyName, o.OrderID
GO

--Select all rows and columns from the
--vew2JoinedViews view in Chapter04.
SELECT *
FROM vew2JoinedViews
GO


I nt roduct ion t o St ored Procedur es
Stor ed pr ocedures are com piled bat ches of T- SQL st at em ent s. The bat ch of
st at em ent s can cont ain near ly all t he T- SQL st at em ent t ypes. While a st ored
procedure can r et urn a resu lt set t he sam e way a v iew does, st ored pr ocedures
are m ore pow erful in several respect s. A view is a virt ual t able; a st or ed
procedure is m or e like a procedure in Visual Basic. You can pass it param et ers,
and it can ret urn values through it s result set , out put param et ers, and ret urn
st at us values. I n fact , st ored procedur es can ret urn m ult iple result set s, while
view s are lim it ed t o a single result sim ilar t o a t able.
Uses for St or ed Pr ocedu r es
Stor ed pr ocedures have four m ain uses. First , t hey can r et urn one or m or e result
set s. You can program a st ored procedure t o ret urn m ult iple result set s as easily
as including m ult iple SELECT st at em ent s w it hin a single st ored procedure.
Anot her way st ored pr ocedures can ret urn r esult set s is via out put param et ers.
An output param et er is a scalar value. A scalar value is a single value, such as a
st ring or an int eger, t hat isn ’t a part of a rowset . While a result set can cont ain a
scalar value, resu lt set s norm ally cont ain set s of values. Out put param et ers
prov ide an efficient m eans for st ored pr ocedures to r et urn scalar values. St ored
procedures can also ret ur n int eger values t hat indicat e how a st ored pr ocedure
term inat es. SQL Serv er docum ent at ion refers to t hese ret ur n values as ret ur n

st at us values. When a st ored procedure can follow any of several int er nal
processing pat hs, ret urn st at us values can indicat e t o a calling rout ine which pat h
a st ored pr ocedure pursued.
A second m aj or use of st ored procedures is t he processing of input param et ers.
These param et ers enable your applicat ions t o cont rol dynam ically t he t hings t hat
a st ored pr ocedure ret urns. Not all T- SQL st at em ent s take param et ers. I n t hese
circum st ances, you can com bine the use of param et ers wit h cont rol- of-flow
st at em ent s, such as I F…ELSE st at em ent s, t o det erm ine what a st or ed procedure
ret ur ns. One com m on use for param et ers is in t he WHERE clause of SELECT
st at em ent s. By using input param et er values as cr it erion values for WHERE
clause expr essions, your applications can dy nam ically control a st ored
procedure’s result set . When users set t he par am et er values, you enable users t o
cont rol an applicat ion dynam ically at run t im e.
Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
A t hird m aj or use for st ored procedur es is t he m anagem ent of
insert / updat e/ delet e operat ions for row sources. I n t his cont ext , a st ored
procedure prov ides value t o an applicat ion w it hout r et urning a r esult set , a
param et er value, or a return st at us value. The procedure sim ply m odifies a row
source. Because st ored procedures can set param et ers based on user input and
the procedures can use param et ers for insert / update/ delet e operat ions, users can
cont rol t he m odificat ions to a row source at run t im e.
Fourt h, you w ill learn how t o use st ored procedures as program s im plem ent ed
wit h a bat ch of T- SQL st at em ent s. This fourt h use under lies and ext ends t he
ot her t hree uses for st ored procedures. These st at em ent s can include SELECT
st at em ent s, ot her st at em ent s for insert / updat e/ delet e operat ions, and cont rol- of-
flow st at em ent s, such as I F…ELSE st at em ent s. I n addit ion, you can sp ecify any of
four t ypes of values— local variables, global variables, param et ers, and ret ur n
st at us values— t o cont rol t he dy nam ic behav ior of a st ored procedure and how it
com m unicat es wit h it s calling procedure.
N ot e

See the “Control- of-Flow” t opic in Book s Online for a good
st ar t ing point that helps you to learn about t radit ional
program m ing techniques for st or ed procedures. Anot her
especially useful Books Online topic for learning about st ored
procedure pr ogram m ing is “Pr ogram m ing St ored
Procedures.”
Re u sing T- SQL St a t em ent s w it h St ored Pr oce dure s
One of t he m aj or advant ages of st ored procedures is that t hey can package T-
SQL st at em ent s for r euse. Four T- SQL st at em ent s help you m anage t hese blocks
of code. Two st at em ent s, CREATE PROCEDURE and ALTER PROCEDURE, enable
the definit ion and refinem ent of the code wit hin a st ored procedure. Wit h t he
DROP PROCEDURE st at em ent, you can rem ove a st or ed pr ocedure from a
dat abase. The EXECUTE st at em ent perm it s you t o run a st ored procedure.
The CREATE PROCEDURE st at em ent let s you creat e a st ored procedure. You can
abbreviat e t his st at em ent as CREATE PROC. Follow t he st at em ent nam e wit h t he
nam e for your st ored pr ocedure. SQL Server has a rich collect ion of syst em
st ored procedures, which t ypically st art wit h sp_. Chapt er 2 includes exam ples of
how t o use syst em st or ed pr ocedures w it h t ables. Syst em st ored procedures are
available for m anaging every aspect of SQL Ser ver perform ance and
adm inist rat ion. To avoid conflict s wit h syst em st ored procedures, avoid st art ing
your own user-defined st or ed procedures w it h t he sp_ prefix. Th is chapt er uses
udp as a prefix for user -defined st ored procedur es. Lik e view nam es, st or ed
procedures should follow t he st andard rules for SQL Server ident ifiers.
The CREATE PROC st at em ent s typically hav e t hree or four m ain elem ent s. First ,
CREATE PROC declares t he st ored procedure and assigns a nam e t o it . Second,
you can specify one or m ore param et ers for t he procedure. The param et er
declarat ions ar e opt ional. Third, t he AS keyword serves as a t ransit ional w ord
bet ween t he declarat ion elem ent s and t he T- SQL code ( t he fourt h elem ent ) t hat
enables a st ored procedure t o perform a t ask . The follow ing t em plat e illust rat es
how t o arrange t hese st ored procedur e elem ent s.

CREATE PROC
procedurename
Parameter specifications

AS
Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.

T-SQL code


Aft er you cr eat e a st ored procedure, y ou can ch ange it s code in at least t wo
different w ays. First , you can invoke t he DROP PROCEDURE ( or DROP PROC)
st at em ent t o rem ove t he pr ior version and t hen invoke a new CREATE PROC
st at em ent wit h t he sam e nam e as t he rem oved procedure. To delet e an exist ing
st ored procedure w it h t he DROP PROC st at em ent , sim ply follow t he keyword
phrase w it h the nam e of t he st ored procedure t hat you want t o rem ove. Wit h t his
approach, you w ipe out any perm issions assigned t o users for t he dropped st ored
procedure. Alt ernat ively, you can invoke t he ALTER PROCEDURE ( or ALTER PROC)
st at em ent . This allows you t o respecify t he param et ers and t he code w it hin a
st ored procedure w hile it m aint ains any perm ission set tings for t he st ored
procedure t hat y ou m odify. Except for t he keyword declaring it , t he ALTER PROC
st at em ent has t he sam e form at as t he CREATE PROC st at em ent .
Your applicat ions can use t he EXECUTE ( or EXEC) st at em ent t o inv ok e a st ored
procedure init ially cr eat ed w it h a CREATE PROC st at em ent. I n it s m ost basic
represent at ion, follow t he EXEC keyword w it h t he nam e of t he st ored procedur e
that you want t o r un. The sy nt ax for t he EXEC st at em ent perm it s you t o assign
values for input param et ers as well as accept out put param et er and ret urn st at us
values. I n addit ion, t he EXEC st at em ent can also ret urn one or m ore result set s—
depending on t he T- SQL code t hat populat es t he st ored procedure. This chapt er
includes num erous sam ples t hat illust rat e t he synt ax for inv oking st ored

procedures w it h t he EXEC st at em ent .
Using Pa r a m et e rs, Loca l Va r ia bles, and Globa l Va riables
Alt hough param et ers, local variables, and global variables can, of course, be used
elsewhere, using t hem wit h st ored procedures especially enhances t he value of
the procedures in an applicat ion. Th ere are t wo basic kinds of param et ers— input
param et ers and out put param et ers. Param et er nam es m ust begin w it h t he @
sym bol. Th e r em ainder of a param eter’s nam e m ust follow t he st andard SQL
Server ident ifier convent ions. Param eters have dat a t ypes t hat correspond t o
those for t able colum n values. (See Chapter 3.)
I nput param et ers perm it y ou t o cust om ize t he operat ion of a st or ed procedure at
run t im e. For exam ple, you can use input param et ers to sp ecify t he colum n
values for a st ored procedure t hat adds a new row t o a row source. Th e CREATE
PROC and ALTER PROC st at em ent s perm it you t o assign default values for input
param et ers. These default values allow a st ored procedure t o use a param et er
wit hout t est ing for a null v alue even if t he user om it s the specificat ion of a
param et er when invoking t he st or ed procedure.
Out put param et ers represent values developed from w it hin a st or ed pr ocedure.
These can be values com put ed by t he procedure or SQL Server. A st ored
procedure can pass back as an out put param et er the I DENTI TY value for a new
row in a t able so t hat anot her st ored pr ocedure can use t he out put par am et er as
a foreign key value for a new row in a relat ed t able. I n t his scenar io, t he out put
param et er value from one st or ed pr ocedure serves as t he input param et er value
for a second one.
A local variable is a m em ory variable t hat you assign for use inside a st ored
procedure. Use t he DECLARE keyword for designat ing local variables and t he SET
keyw ord for assigning v alues t o a local variable. You can also assign a value t o a
local v ar iable with a SELECT st at em ent t hat ret urns a scalar value, such as the
count of t he num ber of rows in a t able. The scope of a local variable is t he st ored
procedure t hat declares t he variable.
Like param et ers, local variable ident ifiers m ust begin wit h t he @ sy m bol. The

rem ainder of t he local v ariable nam e m ust follow st andard SQL Server ident ifier
Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
convent ions. The DECLARE st at em ent for a local variable m ust include a dat a
type for t he var iable. You can use any dat a t ype except for t ext , nt ext, and
im age. A local variable’s dat a t ype specification det erm ines t he t ype of cont ent
that t he var iable can hold. Local var iables can be used in expr essions and as
argum ent s for cont rol- of-flow st at em ent s t o cont rol t he operat ion of a st ored
procedure. Local var iables can w or k in coordinat ion wit h param et ers by accept ing
values from param et ers and passing values t o t hem .
Dev elopers fam iliar wit h SQL Server v ersions pr ior t o 7.0 m ay be fam iliar wit h t he
term global variables. SQL Server 2000 refers t o t hese global variables as
funct ions. A global variable funct ion nam e st art s wit h @@. These global var iable
funct ions ret ur n values t o st or ed procedures t hat cont ain sy st em inform at ion. You
can disp lay t he full list of 33 @@ var iable funct ions from the I ndex tab in Books
Online by ent er ing @@ as t he keyword. This chapt er illust rat es t he use of t he
@@ROWCOUNT funct ion, which ret ur ns t he num ber of r ows affect ed by t he last
T-SQL st at em ent . Ot her @@ funct ions t hat I r egularly find part icular ly convenient
include @@I DENTI TY, @@ERROR, and @@DBTS. Th ese t hr ee funct ions ret urn
the last I DENTI TY value insert ed, t he er ror num ber associat ed wit h t he last T- SQL
st at em ent , and t he cu rrent t im est am p value w it hin a dat abase.


Creat ing a n d Using St ored Procedures
The purpose of t his sect ion is t o int roduce you t o syntax for creat ing and using
st ored procedures. This sect ion shows you t ypical ways of applying t he CREATE
PROC st at em ent . I n addit ion, you learn com m on ways of specifying t he EXEC
st at em ent t o run a st ored procedure. The sect ion illust rat es t echniques for
designat ing input param et ers when you cr eat e a st ored pr ocedure as well as
ways of specifying input param et er values when you run a st or ed procedure.
Dyna m ica lly Select in g fr om a Row Sour ce

One of t he m ain advant ages of st ored procedures com par ed wit h v iews is that
st ored procedures perm it t he use of param et ers. Bot h view s and st or ed
procedures can invoke SELECT st at em ent s. Howev er, st ored procedur es let you
assign values to param et ers in WHERE clause expressions at run t im e. This
capabilit y m eans your applicat ions can t ak e input from users to designat e which
rows a st ored procedur e ret urns in it s result set. Wit h views, you would have t o
preprogram a different view for each set of row s you want ed.
The follow ing scr ipt has t hree bat ches of T-SQL code. The first bat ch rem ov es any
prior version of t he udpList Sh ippersRow in t he current dat abase. The first bat ch
uses t he I NFORMATI ON_SCHEMA.ROUTI NES view t o search for an ex ist ing st ored
procedure wit h t he nam e udpList ShippersRow. I f one already exist s w it h t hat
nam e, t he batch invokes the DROP PROCEDURE st at em ent t o rem ove it .
The second bat ch invokes t he CREATE PROC st at em ent t o cr eat e a new st ored
procedure nam ed udpList ShippersRow. This procedur e t akes a single param et er
nam ed @RowI D w it h an int dat a t ype. The procedur e uses t he param et er t o
specify t he ShipperI D colum n value for t he row it ret urns; see t he WHERE clause
for t he sy nt ax of how t o do t his. The basic SELECT st at em ent ret urns all t he
colum ns from t he Sh ippers t able in t he Nort hwind dat abase. You can t ell from the
synt ax t hat t his is t he SQL Server version of t he dat abase. ( Not ice t he FROM
clause argum ent .) All t he rem aining st ored procedure sam ples use j ust SQL
Server dat abases.
The final bat ch consist s of a single EXEC st at em ent . The st at em ent r uns the
st ored procedure cr eat ed in t he pr evious bat ch and designat es a v alue for t he
Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
RowI D par am et er . Failing to specify a RowI D param et er value causes t he
procedure t o fail wit h an error m essage. Designat ing a nonex ist ent ShipperI D
colum n value w it h RowI D produces an em pt y result set . On t he ot her hand,
specifying any of t he ex ist ing ShipperI D colum n values causes the procedure t o
generat e a r esult set with all t he colum ns for t hat row in t he Sh ippers t able.
--CreateudpListShippersRow

--Delete previous version of udpListShippersRow
--stored procedure if it exists.
IF EXISTS (SELECT ROUTINE_NAME
FROM INFORMATION_SCHEMA.ROUTINES
WHERE ROUTINE_TYPE = ’PROCEDURE’ AND
ROUTINE_NAME = ’udpListShippersRow’)
DROP PROCEDURE udpListShippersRow
GO

--Create udpListShippersRow with an
--input parameter to specify a row.
CREATE PROC udpListShippersRow
@RowID int
AS
SELECT *
FROM Northwind..Shippers
WHERE ShipperID = @RowID
GO

--Run udpListShippersRow with an
--input parameter of 2.
EXEC udpListShippersRow 2

Re t u r ning a Sor t ed Result Set
Even a basic SELECT st at em ent can yield benefit s w hen it is m ade available from
a st ored pr ocedure. For exam ple, t he use of t he ORDER BY clause in a v iew
requires t he concu rrent use of t he TOP predicat e. While t his is cert ainly not
com plicat ed, it is j ust one m ore t hing you hav e t o rem em ber t o get right . The
synt ax for using the ORDER BY clause in a st ored procedure is just like t hat in a
st and-alone T- SQL script . I n ot her words, you don’t need a TOP predicat e for your

SELECT st at em ent .
The follow ing scr ipt shows the ORDER BY clause wit hin a SELECT st at em ent that
det erm ines t he result set from a st ored procedure. The SELECT st at em ent
generat es a resu lt set based on t he Shippers t able, w it h t he rows sort ed by
Com panyNam e colum n values. This r et urns t he rows in a different order t han t he
default one based on t he ShipperI D colum n values. The script again relies on a
three- part st rat egy. The first part rem oves an old version of t he
udpShippersSort edBy Com panyNam e st ored procedure. The second part invokes
the CREATE PROC st at em ent t o add t he new st ored procedur e. The t hird part
runs the newly cr eat ed st ored procedure w it h the EXEC st at em ent . Because t his
st ored procedure doesn’t t ake any param et ers, you can j ust follow t he EXEC
keyw ord wit h t he nam e of t he st ored procedure. There is no need for anyt hing
else aft er t he EXEC key word.
--CreateudpShippersSortedByCompanyName
--Delete previous version of udpShippersSortedByCompanyName
--stored procedure if it exists.
IF EXISTS (SELECT ROUTINE_NAME
FROM INFORMATION_SCHEMA.ROUTINES
WHERE ROUTINE_TYPE = ’PROCEDURE’ AND
ROUTINE_NAME = ’udpShippersSortedByCompanyName’)
DROP PROCEDURE udpShippersSortedByCompanyName
Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
GO

--Create udpShippersSortedByCompanyName with an
--input parameter to specify a row.
CREATE PROC udpShippersSortedByCompanyName
AS
SELECT *
FROM Northwind..Shippers

ORDER BY CompanyName
GO

--Run udpShippersSortedByCompanyName.
EXEC udpShippersSortedByCompanyName
GO

Re t u r ning t h e Scr ipt for a View
Stor ed pr ocedures are an ext rem ely flexible t ool. You can use SELECT stat em ent s
in t he full range of cases t hat use view s and st and-alone T- SQL st at em ent s. For
exam ple, you can query I NFORMATI ON_SCHEMA views t o uncov er inform at ion
about t he obj ect s in a dat abase. An advant age of a st or ed pr ocedure is t hat t he
T-SQL it cont ains is com piled. A st and-alone T- SQL st at em ent m ust be com piled
before SQL Server can use it . Therefore, t he st ored procedure can r un t he sam e
T-SQL code fast er.
N ot e
The sp_executesql syst em st ored procedure offers som e of
the benefit s of st ored procedures for st and- alone T- SQL
SELECT st atem ent s.
The follow ing scr ipt dem onst rat es t he use of a st ored pr ocedure t o query t he
I NFORMATI ON_ SCHEMA.VI EWS view. The resu lt set for t his view cont ains a r ow
for each view in t he cur rent dat abase. The v iew ’s VI EW_DEFI NI TI ON colum n
ret ur ns t he T- SQL script defining a view. The TABLE_NAME colum n ret urns t he
nam e for a view.
The st ored procedure accept s a param et er t hat designat es a view ’s nam e. The
st ored procedure’s SELECT st at em ent passes t he T- SQL scr ipt for a view t o a local
variable, @st rDefinit ion. The local variable accept s t he value in the
VI EW_DEFI NI TI ON colum n value for t he row wit h a TABLE_NAME colum n value
equal t o t he param et er passed t o t he st ored pr ocedure. Then a PRI NT st at em ent
displays t he cont ent s of t he local variable in t he Messages pane.

The st ored procedure’s approach w orks for views wit h up t o 8000 charact ers fr om
the default code page for t he com put er on w hich y ou developed t he st ored
procedure. This is because t he varchar dat a t ype for t he @st rDefinit ion local
variable has a m ax im um lengt h of 8000 charact ers in t he default code page for a
com put er. I f you expect your view scripts t o have m ore charact ers or y our
applicat ion r uns on com put ers using m ult iple code pages, you need anot her
approach for st oring t he view’s T- SQL script . For exam ple, you can use an out put
param et er inst ead of a local var iable. Assign a t ext or an nt ext dat a t ype t o t he
param et er. When using t he out put param et er approach, you can print t he script
in t he calling rout ine for t he st ored procedure. Recall t hat a t ext dat a t ype can
hold up t o 2
31
-1 charact ers, and a dat a t ype value can hold up t o 2
30
-1
charact ers.
Users can alt er t he r et urn value t hat appears in t he Messages pane by changing
the nam e of t he view passed t o t he st ored procedure. The EXEC st at em ent t o
invoke t he st ored pr ocedure encloses t he param et er in single quot at ion m arks.
Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
This is because t he st ored procedure assigns a varchar dat a type t o the
param et er st or ing a view’s nam e.
--CreateudpScriptForView
--Remove prior version of stored procedure.
IF EXISTS (SELECT ROUTINE_NAME
FROM INFORMATION_SCHEMA.ROUTINES
WHERE ROUTINE_TYPE = ’PROCEDURE’ AND
ROUTINE_NAME = ’udpScriptForView’)
DROP PROCEDURE udpScriptForView
GO


--Create stored procedure to print definition
--for a view in the current database.
CREATE PROC udpScriptForView
@vewName varchar(128)
AS
DECLARE @strDefinition varchar(8000)
SET @strDefinition = (SELECT VIEW_DEFINITION
FROM INFORMATION_SCHEMA.VIEWS
WHERE TABLE_NAME = @vewName)
PRINT @strDefinition
GO

--Run stored procedure and pass view name.
EXEC udpScriptForView ’vewShippers’
GO


Processing St ored Procedure Output s
One of t he t asks t hat st ored procedures serve especially well is get t ing dat a back
to a calling procedure. St or ed pr ocedures can achieve t his goal in several ways.
First , t hey perm it t he t ransf er of dat a back t o t he calling procedure in t he form of
result set s. You can ret urn m ult iple result set s from a single st ored procedur e.
Second, a st ored procedure can r et urn scalar values via out put param et ers.
Third, code calling a st ored pr ocedure can process ret urn st at us values. I n any
one applicat ion, y ou can concu rrent ly use any com binat ion of t hese t hree
processes for ret ur ning values. This sect ion elaborat es on t hem and dem onst rat es
the sy nt ax for im plem ent ing each .
Re t u r ning Tw o Result Set s fr om a St or ed Procedu r e
I t ’s sim ple t o ret ur n m ult iple resu lt set s from a single st ored pr ocedure: j ust

include a separat e SELECT st at em ent for each r esult set t hat y ou want a st ored
procedure t o ret urn. I n contrast , views can hav e only a single SELECT st at em ent .
Once y ou st art using m ult iple SELECT st at em ent s in a st or ed pr ocedure, you’ll
find t hat it has considerably m ore flex ibilit y t han ret urning rows from a t able or
view .
The follow ing scr ipt cr eat es a st ored procedur e wit h t w o result set s. The first
result set cont ains a row w it h t he nam e and cr eat ion dat e for each user- defined
st ored procedure in a dat abase. Recall t hat t he dat abase cont ext for t hese
sam ples is Chapt er04. (You can set t he cont ext wit h a USE st at em ent.) To ret urn
j ust t he user -defined st or ed procedur es from the
I NFORMATI ON_ SCHEMA.ROUTI NES view, you need t wo crit eria expressions. One
expression select s j ust rows wit h a ROUTI NE_TYPE colum n value of PROCEDURE.
This expression filt ers out any user- defined funct ions. The second expr ession
Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
rem oves any rows wit h a ROUTI NE_NAME colum n value t hat begins w it h dt _.
Because SQL Server uses dt _ as a prefix for t he st ored procedures t hat it cr eat es
in a dat abase, t his expr ession leaves only user-defined st ored procedures.
The second SELECT st at em ent ret urns t he value of t he @@ROWCOUNT funct ion.
This funct ion is always t he value of r ecords affect ed by t he last T- SQL st at em ent .
I n t his case, t he last one ret ur ns the nam es and cr eat ion dat es of the user-
defined st ored procedures in a dat abase, so t he second SELECT st at em ent
ret ur ns t he num ber of user- defined st or ed procedures in t he current database
cont ext .
--CreateudpReturn2ResultSets
--Remove prior version of stored procedure.
IF EXISTS (SELECT ROUTINE_NAME
FROM INFORMATION_SCHEMA.ROUTINES
WHERE ROUTINE_TYPE = ’PROCEDURE’ AND
ROUTINE_NAME = ’udpReturn2ResultSets’)
DROP PROCEDURE udpReturn2ResultSets

GO

--Create stored procedure to return one result
--set for listing stored procedure names and dates
--and another with the count of the stored procedures.
CREATE PROC udpReturn2ResultSets
AS
SELECT ROUTINE_NAME, CREATED
FROM INFORMATION_SCHEMA.ROUTINES
WHERE ROUTINE_TYPE = ’PROCEDURE’ AND
LEFT(ROUTINE_NAME,3) <> ’dt_’
ORDER BY CREATED DESC
SELECT @@ROWCOUNT ’Number of stored procedures’
GO

--Run stored procedure that returns two result sets.
EXEC udpReturn2ResultSets
GO

Figure 4- 3 sh ow s t he out put from running t he udpRet urn2Result Set s st ored
procedure. (This is t he out put from the preceding script .) Not ice t hat t he t op
result set cont ains ROUTI NE_NAME and CREATED colum n values. This resu lt has
a row for each user -defined st ored procedure. The last row includes t he nam e and
creat ion dat e for t he elevent h st ored procedure. The second result set cont ains a
num ber t hat is t he count of t he num ber of user- defined st ored procedures— 11.
Figur e 4 - 3 . Th e ret u r n fr om a u ser- d efined st ored pr oced ur e that
spe cifies t w o resu lt se ts.
Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.

Re t u r ning One Result Set and One Pa ra m et e r Va lue

The preceding sam ple uses a SELECT st at em ent t o ret urn a scalar value, nam ely
the cur rent value for @@ROWCOUNT. By entering t he @@ROWCOUNT global
variable funct ion in a SELECT st at em ent , t he sam ple r et urns t he current value of
@@ROWCOUNT in a result set . The next sam ple illust rat es how t o ret ur n t he
@@ROWCOUNT value as an out put param et er from a st ored procedure. This
involves a special declarat ion for t he param et er inside t he st ored procedure as
well as an assignm ent expression in t he EXEC st at em ent t o ret riev e t he value for
the out put param et er. I n t he T- SQL code t hat calls t he st or ed procedur e, you
need t o t ransfer t he out put param et er t o a local var iable for use locally. I n
addit ion, t he EXEC st at em ent m ust explicit ly designat e t he output param et er.
The follow ing code show s t he exact sy ntax for ret ur ning @@ROWCOUNT as an
out put param et er. First not ice t he line im m ediat ely aft er t he CREATE PROC
st at em ent :
@NumberOfRows int OUTPUT

This line declares t he param et er. Not ice t hat it ends wit h t he keyw ord OUTPUT.
This keyw ord designat es t he @Num berOfRows param et er as an out put
param et er. Lat er in t he st ored procedure, a SET st at em ent assigns the current
value of @@ROWCOUNT t o t he @Num berOfRow s param et er , like t his:
SET @NumberOfRows = (SELECT @@ROWCOUNT)

This st ored pr ocedure div erges from t he preceding one by ex plicit ly invoking t he
SET NOCOUNT st at em ent w it h t he value ON. This st at em ent suppresses the
aut om at ic SQL Server m essage about t he num ber of r ows affect ed, which
happens t o be t he value of @@ROWCOUNT. At t he conclusion of t he st ored
procedure, t he sam ple invokes t he SET NOCOUNT st at em ent a second t im e w it h
the set t ing OFF. This second invocat ion of t he SET NOCOUNT st at em ent rest ores
the default behav ior of print ing t he rows affect ed by a T- SQL st at em ent.
Using a param et er ret urned by a st ored procedure also r equires special sy nt ax.
First you need a local variable t o accept t he out put param et er value. This is

because you cannot w ork direct ly wit h t he out put param et er in t he code that calls
the st or ed pr ocedure. The sam ple code declares a local variable nam ed
@Ret urnedParam Value t o st ore t he out put param et er value locally. Second you
need an assignm ent st atem ent . This st at em ent m ust end wit h t he OUTPUT
keyw ord. I n addit ion, t he local variable m ust be on t he right side of t he equal
Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
sign, and t he out put par am eter should appear on t he left side. Th ird t he out put
param et er ret ur ns an int dat a t ype value. However, t he Print st at em ent that
report s t he num ber of st ored procedures r equires a charact er dat a t ype, nam ely
varchar. Therefore, t he code applies the CAST funct ion t o t he local variable
st oring t he out put param et er value; t he funct ion represent s t he int eger value as
a st ring. The expression for @st rFor Pr int er com bines a st ring const ant wit h t he
CAST funct ion value. The PRI NT st atem ent t akes @st rForPrint er as it s argum ent
to print t he num ber of st ored procedures wit h a br ief descr ipt ive label.
--CreateudpReturn1ResultSet1Parameter
--Remove prior version of stored procedure.
IF EXISTS (SELECT ROUTINE_NAME
FROM INFORMATION_SCHEMA.ROUTINES
WHERE ROUTINE_TYPE = ’PROCEDURE’ AND
ROUTINE_NAME = ’udpReturn1ResultSet1Parameter’)
DROP PROCEDURE udpReturn1ResultSet1Parameter
GO

--Create stored procedure to return one result
--set for listing stored procedure names and dates along
--with another containing the count of the stored procedures.
CREATE PROC udpReturn1ResultSet1Parameter
@NumberOfRows int OUTPUT
AS
SET NOCOUNT ON

SELECT ROUTINE_NAME, CREATED
FROM INFORMATION_SCHEMA.ROUTINES
WHERE ROUTINE_TYPE = ’PROCEDURE’ AND
LEFT(ROUTINE_NAME,3) <> ’dt_’
ORDER BY CREATED DESC
SET @NumberOfRows = (SELECT @@ROWCOUNT)
SET NOCOUNT OFF
GO

--Run stored procedure that returns two result sets.
DECLARE @ReturnedParamValue int
DECLARE @strForPrinter varchar(100)
EXEC udpReturn1ResultSet1Parameter
@NumberOfRows = @ReturnedParamValue OUTPUT
SET @strForPrinter = ’Number of stored procs: ’ +
Cast(@ReturnedParamValue AS varchar(3))
PRINT @strForPrinter
GO

Re t u r ning One St r ing Pa ra m et er
The code y ou use t o ret urn a st ring value as an out put param et er is essent ially
the sam e code y ou use t o ret urn a num ber value. The m ain dist inct ion is t he
declarat ion of t he dat a t ype for t he param et er.
The follow ing scr ipt returns t he nam e of t he oldest user-defined st ored procedure
in a dat abase. I t passes back t he nam e of t he st ored procedur e via an out put
param et er nam ed @st rNam eOfOldest SProc. Not ice t hat t he out put par am et er
declarat ion uses a varch ar dat a t ype t hat is consist ent w it h t he m axim um lengt h
of a SQL Serv er ident ifier . I f your applicat ion runs in m ult iple locat ions t hat use
different code pages, you m ay want t o use an nvarchar rat her t han a varchar
dat a t ype specificat ion for t he param et er.

I n t his case, t he t echnique for finding t he st ored procedure is as int erest ing as
the t ech nique for declaring t he out put param et er. The SET ROWCOUNT st at em ent
tells SQL Server t o st op processing a st at em ent aft er t he designat ed num ber of
Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
records. The ORDER BY clause in t he SELECT st at em ent sorts t he st ored
procedures so t hat the nam e of t he oldest st ored procedur e appears first .
Ther efor e, st opping after processing the first row ret urns t he oldest st ored
procedure.
The t echnique for processing an out put param et er in t he calling r out ine is about
the sam e whet her t he out put param eter has an int or a varchar dat a t ype. This
part icu lar sam ple appears slight ly sim pler t han t he preceding one m ost ly because
it doesn’t label t he ret ur n value t hat is pr int ed in t he Messages pane. Because t he
local v ar iable for holding t he out put param et er is already a st ring, t her e is no
need t o convert it so t hat it can be used as an argum ent for t he PRI NT st at em ent .
--CreateudpReturn1StringParameter
--Remove prior version of stored procedure.
IF EXISTS (SELECT ROUTINE_NAME
FROM INFORMATION_SCHEMA.ROUTINES
WHERE ROUTINE_TYPE = ’PROCEDURE’ AND
ROUTINE_NAME = ’udpReturn1StringParameter’)
DROP PROCEDURE udpReturn1StringParameter
GO

--Create stored procedure to return one
--parameter with a string value.
CREATE PROC udpReturn1StringParameter
@strNameOfOldestSProc varchar(128) OUTPUT
AS
SET ROWCOUNT 1
SET @strNameOfOldestSProc = (SELECT TOP 1 ROUTINE_NAME

FROM INFORMATION_SCHEMA.ROUTINES
WHERE LEFT(ROUTINE_NAME,3) <> ’dt_’
AND ROUTINE_TYPE = ’PROCEDURE’
ORDER BY CREATED)
GO

--Run stored procedure that returns one string parameter.
DECLARE @ReturnedParamValue varchar(128)
EXEC udpReturn1StringParameter
@strNameOfOldestSProc = @ReturnedParamValue OUTPUT
PRINT @ReturnedParamValue
GO

W or king w it h Re t ur n St a t u s V a lues
Stor ed pr ocedures considered t o t his point in t he chapt er proceed in a st raight
line fr om t he first to t he last st at em ent in t he procedure. However, t his isn’t a
requirem ent . Cont rol- of- flow st at em ents, such as t he I F…ELSE st at em ent , m ake it
possible for a st ored procedur e t o execu te condit ionally. You can end the
processing w it hin a st ored procedure wit h one or m ore RETURN st at em ent s at the
end of each of several pat hs t hrough t he code. Each RETURN st at em ent can pass
back an in t dat a t ype value t o t he calling procedure as it closes t he st ored
procedure. Alt hough you can have m ult iple RETURN st atem ent s wit h different
ret ur n st at us values, any one invocat ion of a st ored procedure can r et urn j ust one
ret ur n st at us value. This m akes it possible for code inv ok ing a st ored procedure
to k now precisely at w hich line t he st ored procedure closed.
The follow ing code sam ple creat es a st ored procedure t hat searches for a st ored
procedure by a nam e in a dat abase. I f t he search finds a st ored procedure wit h
the t arget nam e, t he r et ur n st at us value is 1. Ot herwise, t he ret urn st at us value
is 0. I t is com m on t o set ret ur n st at us values with a RETURN st at em ent inside an
I F…ELSE st at em ent ( alt hough t his sam ple’s design is ext raordinarily sim ple) .

Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
The calling T- SQL code for t he st or ed procedure in t he following sam ple causes
the procedure t o search for eit her of t wo nam es: udpList Sh ippersRow or SP1.
Make sur e your dat abase has a st ored procedur e nam ed udpList Shipper sRow and
that your dat abase doesn ’t have a st or ed pr ocedure nam ed SP1. I f you have been
doing t he sam ples in t he order t hat t hey appear in this chapt er, your Chapt er04
dat abase will have a st ored procedure nam ed udpList ShippersRow. This let s you
use t he sam ple T- SQL code t hat calls t he st ored procedure to verify t hat t he
ret ur n st at us values reflect the presence or absence of a st ored procedur e. The
calling T- SQL code for t he st or ed pr ocedure displays t he ret ur n st at us value in a
result set that cont ains eit her 0 or 1. These values m at ch each of t he ret urn
st at us values set in t he st ored procedure.
The sy nt ax for capt uring a ret urn st at us value in a calling procedure deviates
slight ly fr om t hat for an out put param et er. I n bot h cases, you need a local
variable to represent t he value r et urned from t he st ored procedure. However , t o
capt ure t he ret ur n st at us value, you use an assignm ent expression t hat set s t he
st ored procedure equal to the local variable for t he ret ur n st at us value. This
assignm ent expr ession is act ually int egrat ed int o t he call of t he st ored procedur e
as an argum ent for an EXEC st at em ent .
I n t he sam ple, a local variable specifies t he v alue for t he procedure t o pass t o t he
st ored procedure. As t he code appears, t he calling code passes t he nam e
udpList ShippersRow. However, you can com m ent out ( w it h two leading hyphens)
the assignm ent st at em ent for t he @st r ProcNam e local variable and rem ove t he
hyphens from t he assignm ent st at em ent t hat set s t he local variable t o SP1. This
transit ion will cause t he ret urn st at us value t o sw it ch fr om 1 t o 0.
--CreateudpReturnStatusValue
--Remove prior version of stored procedure.
IF EXISTS (SELECT ROUTINE_NAME
FROM INFORMATION_SCHEMA.ROUTINES
WHERE ROUTINE_TYPE = ’PROCEDURE’ AND

ROUTINE_NAME = ’udpReturnStatusValue’)
DROP PROCEDURE udpReturnStatusValue
GO

--Create stored procedure to pass back
--a return status value of 0 or 1.
CREATE PROC udpReturnStatusValue
@strName varchar(123)
AS
SELECT ROUTINE_NAME
FROM INFORMATION_SCHEMA.ROUTINES
WHERE ROUTINE_NAME = @strName AND ROUTINE_TYPE = ’PROCEDURE’
IF @@ROWCOUNT = 0
RETURN 0
ELSE
RETURN 1
GO

--Pass a procedure name to udpReturnStatusValue.
DECLARE @strProcName varchar(128)
DECLARE @return_status int

--Use the following SET statement for a 1.
SET @strProcName = ’udpListShippersRow’

--Use the following SET statement for a 0.
--SET @strProcName = ’SP1’

EXEC @return_status = udpReturnStatusValue @strProcName
SELECT @return_status AS ’Return Status’

Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.

×