+ All Categories
Home > Education > SQL Server Stored procedures

SQL Server Stored procedures

Date post: 18-Nov-2014
Category:
Upload: randy-riness-south-puget-sound-community-college
View: 2,100 times
Download: 2 times
Share this document with a friend
Description:
 
Popular Tags:
39
Stored Procedures Stored Procedures CIS-282 CIS-282
Transcript
Page 1: SQL Server Stored procedures

Stored ProceduresStored Procedures

CIS-282CIS-282

Page 2: SQL Server Stored procedures

Scripts v. Stored Scripts v. Stored ProceduresProcedures

Script: Text file of SQL commandsScript: Text file of SQL commands Stored Procedure: SQL commands Stored Procedure: SQL commands

stored in database itselfstored in database itself– SPROC’s have more capabilities SPROC’s have more capabilities

than a scriptthan a script

Page 3: SQL Server Stored procedures

BATCHBATCH

Batch is a logical group of SQL Batch is a logical group of SQL statementsstatements– Run-time error will halt execution Run-time error will halt execution

only of FURTHER stepsonly of FURTHER steps Can break up multiple steps using GOCan break up multiple steps using GO

– Not available in all toolsNot available in all tools– GO causes editing tool to send GO causes editing tool to send

statements to that point for statements to that point for executionexecution

– GO isn’t sent to SQL ServerGO isn’t sent to SQL Server

Page 4: SQL Server Stored procedures

Format of SPROC’sFormat of SPROC’s

CREATE PROCEDURE <name> CREATE PROCEDURE <name>

<parameter list><parameter list>

ASAS

<instructions to execute><instructions to execute>

Page 5: SQL Server Stored procedures

EXECUTEEXECUTE

EXEC(cute) EXEC(cute) statementstatementOROR

EXEC(cute) EXEC(cute) stored procedure namestored procedure name Statement or sproc runs in it’s Statement or sproc runs in it’s

own scopeown scope– Can’t ‘share’ variables directlyCan’t ‘share’ variables directly– User’s security rules applyUser’s security rules apply– Can’t be used in User Defined Can’t be used in User Defined

Function (UDF)Function (UDF)

Page 6: SQL Server Stored procedures

Uses of Stored Uses of Stored ProceduresProcedures

For returning data (select)For returning data (select) For editing dataFor editing data For calculationsFor calculations

Page 7: SQL Server Stored procedures

ParametersParameters

Method for sending data into and from Method for sending data into and from a stored procedurea stored procedure– INPUT parameters are values sent inINPUT parameters are values sent in– OUTPUT parameters are values OUTPUT parameters are values

returnedreturned Must have a holding space Must have a holding space (variable) for the returned data(variable) for the returned data

Defined before start of procedure (AS)Defined before start of procedure (AS)

Page 8: SQL Server Stored procedures

Declaring ParametersDeclaring Parameters

Include name and datatypeInclude name and datatype Default value is optionalDefault value is optional

– Without a default value, Without a default value, parameter is requiredparameter is required

Direction is optional (input is Direction is optional (input is default)default)– An output parameter must have An output parameter must have

direction specifieddirection specified

Page 9: SQL Server Stored procedures

Sample Input ParameterSample Input Parameter

CREATE PROC upFindStudentCREATE PROC upFindStudent

@SID char(9)@SID char(9)

ASAS

SELECT * SELECT *

FROM Students_TFROM Students_T

Where SchoolID=@SIDWhere SchoolID=@SID

Page 10: SQL Server Stored procedures

Sample Output Sample Output ParameterParameter

CREATE PROC upFindStudentIDCREATE PROC upFindStudentID

@First varchar(25),@First varchar(25),

@Last varchar(35),@Last varchar(35),

@SID char(9) OUTPUT@SID char(9) OUTPUT

ASAS

SELECT @SID=SchoolIDSELECT @SID=SchoolID

FROM Students_TFROM Students_T

Where @First=Firstname and Where @First=Firstname and

@Last=Lastname@Last=Lastname

Page 11: SQL Server Stored procedures

Return ValuesReturn Values

Result of stored procedure Result of stored procedure indicates success or failureindicates success or failure

Non-zero value indicates a problemNon-zero value indicates a problem Must be an integerMust be an integer Different from an output parameterDifferent from an output parameter

– Output parameter is about Output parameter is about datadata RETURN <value>RETURN <value>

– Causes immediate exit Causes immediate exit

Page 12: SQL Server Stored procedures

VariablesVariables

Create using DECLARECreate using DECLARE Need to start with ‘@’Need to start with ‘@’ Can use SQL data types or custom Can use SQL data types or custom

data typesdata types

DECLARE @StudentName DECLARE @StudentName varchar(50)varchar(50)

Page 13: SQL Server Stored procedures

Variable AssignmentVariable Assignment

SET is usually used similar to SET is usually used similar to procedural languageprocedural language

SET @Var=valueSET @Var=value

SELECT is usually used when SELECT is usually used when getting a value from a querygetting a value from a query

SELECT SELECT @Var=Sum(PossiblePoints) @Var=Sum(PossiblePoints) FROM AssignmentsFROM Assignments

Page 14: SQL Server Stored procedures

Decision MakingDecision Making

SQL supports two structures for SQL supports two structures for branching:branching:– IFIF– CASECASE

Both structures are similar to Both structures are similar to other languages (IF … THEN, other languages (IF … THEN, SELECT CASE) SELECT CASE)

Both structures tend to have Both structures tend to have specific places where usedspecific places where used

Page 15: SQL Server Stored procedures

IF BlocksIF Blocks

IF … ELSEIF … ELSE– No end ifNo end if– Need to use Begin/End if have more Need to use Begin/End if have more

than one instruction to executethan one instruction to execute

IF StartDate < EndDateIF StartDate < EndDate

BeginBegin

……

EndEnd

ELSEELSE

Page 16: SQL Server Stored procedures

Simple Case StatementSimple Case Statement

CASECASE– Similar to SELECT CASESimilar to SELECT CASE– Compares one value to Compares one value to

different casesdifferent casesCASE CategoryCASE Category

WHEN ‘pop_comp’ THEN ‘Popular Computing’WHEN ‘pop_comp’ THEN ‘Popular Computing’

WHEN ‘mod_cook’ THEN ‘Modern Cooking’WHEN ‘mod_cook’ THEN ‘Modern Cooking’

ENDEND

Page 17: SQL Server Stored procedures

Searched CASESearched CASE

No test expressionNo test expression Each WHEN has a boolean testEach WHEN has a boolean test

CASECASE

WHEN Points >= 90 THEN ‘A’WHEN Points >= 90 THEN ‘A’

WHEN Points < 90 AND Extra > 0WHEN Points < 90 AND Extra > 0

THEN ‘A’THEN ‘A’

ENDEND

Page 18: SQL Server Stored procedures

Looping (While)Looping (While)

Typically used with a CURSORTypically used with a CURSOR– Cursor data type allows a table Cursor data type allows a table

to be stored in memory and to be stored in memory and each row/field to be accessedeach row/field to be accessed

BREAK allows early exit from loopBREAK allows early exit from loop CONTINUE forces control to start CONTINUE forces control to start

of loopof loop Working with sets is preferred Working with sets is preferred

over loops (SQL is about sets)over loops (SQL is about sets)

Page 19: SQL Server Stored procedures

Finding Identity ValuesFinding Identity Values

When need to find the value used When need to find the value used to identify the last row addedto identify the last row added

@@Identity@@Identity Scope_IdentityScope_Identity Ident_CurrentIdent_Current

Page 20: SQL Server Stored procedures

@@Identity – @@Identity – System VariableSystem Variable

Returns the last identity value used Returns the last identity value used as a result of INSERT or SELECT INTOas a result of INSERT or SELECT INTO– Not limited to current scope; may Not limited to current scope; may

not get correct valuenot get correct value Returns Null if operation failed or a Returns Null if operation failed or a

value wasn’t generatedvalue wasn’t generated Returns last number created if Returns last number created if

multiple inserts occur (i.e. SELECT multiple inserts occur (i.e. SELECT INTO)INTO)

Page 21: SQL Server Stored procedures

Scope_Identity()Scope_Identity()

Return the last identity values generated in any table in the current session.

Returns values inserted only within the current scope– Not affected by other

operations.

Page 22: SQL Server Stored procedures

Ident_Current()Ident_Current()

Not limited by scope and session; Limited to a specified table (table

name specified as an argument value).

Page 23: SQL Server Stored procedures

@@Rowcount –@@Rowcount – System Variables System Variables

Number of rows returned or Number of rows returned or affected by the last statementaffected by the last statement

0 (zero) is often used as a logical 0 (zero) is often used as a logical testtest– If no records found for where If no records found for where

clause, notify system or processclause, notify system or process

Page 24: SQL Server Stored procedures

ErrorsErrors

Errors can occur because of SQL Errors can occur because of SQL statementstatement– Invalid syntax, or data typeInvalid syntax, or data type

Errors can also reflect business Errors can also reflect business rulesrules– Data doesn’t match Data doesn’t match

requirementsrequirements

Page 25: SQL Server Stored procedures

@@Error – @@Error – System VariableSystem Variable

Determined after each SQL Determined after each SQL statement;statement;

0 means statement was successful0 means statement was successful Number other than zero is Number other than zero is

typically a specific errortypically a specific error Can store value in variable and Can store value in variable and

testtest

Page 26: SQL Server Stored procedures

Try/CatchTry/Catch

Similar to .Net languagesSimilar to .Net languages Need to include BEGIN/ENDNeed to include BEGIN/END

BEGIN TRYBEGIN TRY

<code><code>

END TRYEND TRY

BEGIN CATCHBEGIN CATCH

<error handling code><error handling code>

END CATCHEND CATCH

Page 27: SQL Server Stored procedures

Raise ErrorRaise Error

Used to send information to Used to send information to calling programcalling program

Syntax:Syntax:RaisError (Message string OR RaisError (Message string OR

Message ID, Severity, State)Message ID, Severity, State)– Severity – <14 information; 15-19 Severity – <14 information; 15-19

warning or user can correct; 20+ fatalwarning or user can correct; 20+ fatal– State – way to differentiate problems State – way to differentiate problems

if needed; typically use 1if needed; typically use 1 RAISERROR (50001,16,1)RAISERROR (50001,16,1)

Page 28: SQL Server Stored procedures

Error Message Error Message

Message ID or StringMessage ID or String– Use ID if have custom or TSQL Use ID if have custom or TSQL

error to useerror to use– Use String for ‘on the fly’ Use String for ‘on the fly’

messagemessage Stored Error Messages are server-Stored Error Messages are server-

specificspecific– Can add messageCan add message– Number greater than 50000Number greater than 50000

Page 29: SQL Server Stored procedures

Custom Error MessagesCustom Error Messages

Messages can include a parameter Messages can include a parameter with % to allow addition to with % to allow addition to messagemessage– ‘‘D’ – signed integerD’ – signed integer– ‘‘O’ – unsigned octalO’ – unsigned octal– ‘‘P’ – pointerP’ – pointer– ‘‘S’ – stringS’ – string– ‘‘U’ – unsigned integerU’ – unsigned integer– ‘‘X’ or ‘x’ – unsigned hexadecimalX’ or ‘x’ – unsigned hexadecimal

Page 30: SQL Server Stored procedures

Severity & StateSeverity & State

1 – 18: Informational1 – 18: Informational– 11 – 16 typically raise error at 11 – 16 typically raise error at

clientclient 19 – 25: Severe error19 – 25: Severe error

– 20+ is fatal error and connection 20+ is fatal error and connection will terminatewill terminate

State is ‘ad hoc’ and can help if same State is ‘ad hoc’ and can help if same error happens in multiple placeserror happens in multiple places– Range of 1 – 127Range of 1 – 127

Page 31: SQL Server Stored procedures

Sample Error MessageSample Error Message

RaisError(“Operation cannot be RaisError(“Operation cannot be completed because field %s completed because field %s cannot be null”,1,1,”fieldname”)cannot be null”,1,1,”fieldname”)

Page 32: SQL Server Stored procedures

TransactionsTransactions

Provides method for canceling an Provides method for canceling an operationoperation

Can restore rows, columns to Can restore rows, columns to original state in event of error or original state in event of error or business logic failurebusiness logic failure

Use when changes will either be Use when changes will either be committed or discarded in entiretycommitted or discarded in entirety

Page 33: SQL Server Stored procedures

ACIDACID

AtomicityAtomicity: All of the changes will be : All of the changes will be accepted or none of the changes will be accepted or none of the changes will be acceptedaccepted

ConsistencyConsistency: Data is either in its original : Data is either in its original or changed stateor changed state

IsolationIsolation: If multiple transactions occur, : If multiple transactions occur, data is never available in an intermediate data is never available in an intermediate statestate

DurabilityDurability: Once finished, all changes are : Once finished, all changes are complete and changes can only be done by complete and changes can only be done by another transaction/unit of workanother transaction/unit of work

Page 34: SQL Server Stored procedures

Using A TransactionUsing A Transaction

Begin Tran: Identifies the startBegin Tran: Identifies the start Commit Tran: Write changesCommit Tran: Write changes Rollback Tran: Cancel changesRollback Tran: Cancel changes

Issue A Commit Or Rollback Or Issue A Commit Or Rollback Or Connection Stays Open Until Connection Stays Open Until TerminatedTerminated

Page 35: SQL Server Stored procedures

Locking & ConcurrencyLocking & Concurrency

Locking allows a transaction to Locking allows a transaction to ensure that it can rollbackensure that it can rollback

Prevents other operations from Prevents other operations from changing that datachanging that data

Concurrency refers to multiple Concurrency refers to multiple actions running against database actions running against database at the same timeat the same time– What happens if you want to What happens if you want to

change data I’m working with?change data I’m working with?

Page 36: SQL Server Stored procedures

Sample Locking LevelsSample Locking Levels

DatabaseDatabase TableTable Extent (memory)Extent (memory) Page (subset of Page (subset of

extent)extent) KeyKey RowRow

Page 37: SQL Server Stored procedures

CursorsCursors

Processing based on each rowProcessing based on each row– not set operationsnot set operations

Declare @Cursor CursorDeclare @Cursor Cursor Set @Cursor = Cursor For (select Set @Cursor = Cursor For (select

statement)statement) Open @CursorOpen @Cursor Fetch Next From @Cursor into Fetch Next From @Cursor into

(variables matching field list in (variables matching field list in select)select)

Page 38: SQL Server Stored procedures

Using a CursorUsing a Cursor

Declare @Students CursorDeclare @Students CursorSet @Cursor = Cursor For (Select FirstName, Set @Cursor = Cursor For (Select FirstName,

LastName From Students)LastName From Students)Open @StudentsOpen @StudentsWhile @@Fetch_Status = 0While @@Fetch_Status = 0

BeginBeginFetch Next From @Students Into @First, Fetch Next From @Students Into @First, @Last@LastPrint @First + ‘ ‘+ @Last Print @First + ‘ ‘+ @Last EndEnd

Close @StudentsClose @StudentsDeallocate @StudentsDeallocate @Students

Page 39: SQL Server Stored procedures

@@Fetch_Status@@Fetch_Status

0 success;0 success; -1 failed (read record outside -1 failed (read record outside

recordset);recordset); -2 missing record (eg. someone -2 missing record (eg. someone

else deleted)else deleted)


Recommended