Storedprocedures 101101092927 Phpapp01
Storedprocedures 101101092927 Phpapp01
CIS-282
Scripts v. Stored
Procedures
Script: Text file of SQL commands
Stored Procedure: SQL commands
stored in database itself
– SPROC’s have more capabilities than
a script
BATCH
EXEC(cute) statement
OR
EXEC(cute) stored procedure name
Statement or sproc runs in it’s own
scope
– Can’t ‘share’ variables directly
– User’s security rules apply
– Can’t be used in User Defined
Function (UDF)
Uses of Stored Procedures
IF … ELSE
– No end if
– Need to use Begin/End if have more than
one instruction to execute
IF StartDate < EndDate
Begin
…
End
ELSE
Simple Case Statement
CASE
– Similar to SELECT CASE
– Compares one value to different
cases
CASE Category
WHEN ‘pop_comp’ THEN ‘Popular Computing’
WHEN ‘mod_cook’ THEN ‘Modern Cooking’
END
Searched CASE
No test expression
Each WHEN has a boolean test
CASE
WHEN Points >= 90 THEN ‘A’
WHEN Points < 90 AND Extra > 0
THEN ‘A’
END
Looping (While)
Message ID or String
– Use ID if have custom or TSQL error
to use
– Use String for ‘on the fly’ message
Stored Error Messages are server-
specific
– Can add message
– Number greater than 50000
Custom Error Messages
1 – 18: Informational
– 11 – 16 typically raise error at client
19 – 25: Severe error
– 20+ is fatal error and connection will
terminate
State is ‘ad hoc’ and can help if same
error happens in multiple places
– Range of 1 – 127
Sample Error Message
RaisError(“Operation cannot be
completed because field %s cannot be
null”,1,1,”fieldname”)
Transactions
Database
Table
Extent (memory)
Page (subset of
extent)
Key
Row
Cursors
0 success;
-1 failed (read record outside
recordset);
-2 missing record (eg. someone else
deleted)