BIT275/276 Instructor: Craig Duckett Email: [email protected] .

41
Stored Procedures, Transactions, and Error-Handling BIT275/276 Instructor: Craig Duckett Email: [email protected] http:// www.dotnet-tricks.com/Tutorial/sqlserver/IbUO310312-Different-Types-of-SQL-Server-Stored-Proc edures.html http :// www.dotnet-tricks.com/Tutorial/sqlserver/KY3T010412-Different-Types-of-SQL-Server-Functions.h tml

Transcript of BIT275/276 Instructor: Craig Duckett Email: [email protected] .

Stored Procedures

Stored Procedures, Transactions, and Error-HandlingBIT275/276Instructor: Craig DuckettEmail: [email protected]://www.dotnet-tricks.com/Tutorial/sqlserver/IbUO310312-Different-Types-of-SQL-Server-Stored-Procedures.htmlhttp://www.dotnet-tricks.com/Tutorial/sqlserver/KY3T010412-Different-Types-of-SQL-Server-Functions.html 1Stored Procedures6/2/2015Stored Procedure vs. ViewA Stored Procedure: accepts parameters can NOT be used as building block in a larger query can contain several statements, loops, IF ELSE, etc. can perform modifications to one or several tables can NOT be used as the target of an INSERT, UPDATE or DELETE statement.

A View: does NOT accept parameters CAN be used as building block in a larger query can contain only one single SELECT query can NOT perform modifications to any table but can (sometimes) be used as the target of an INSERT, UPDATE or DELETE statement. Stored Procedure vs. FunctionBasic DifferenceFunction must return a value but in Stored Procedure it is optional ( Procedure can return zero or n values).Functions can have only input parameters for it whereas Procedures can have input/output parameters .Functions can be called from Procedure whereas Procedures cannot be called from Function.

Advance Difference Procedure allows SELECT as well as DML(INSERT/UPDATE/DELETE) statement in it whereas Function allows only SELECT statement in it.Procedures can not be utilized in a SELECT statement whereas Function can be embedded in a SELECT statement.Stored Procedures can NOT be used in the SQL statements anywhere in the WHERE/HAVING/SELECT section whereas Function can be.The most important feature of stored procedures over function is to retention and reuse the execution plan while in case of function it will be compiled every time.Functions that return tables can be treated as another rowset. This can be used in JOINs with other tables.Inline Function can be though of as views that take parameters and can be used in JOINs and other Rowset operations.Exception can be handled by TRY-CATCH block in a Procedure whereas a TRY-CATCH block can NOT be used in a Function.We can go for Transaction Management in Procedure whereas we can't go in Function.

Scripts v. Stored ProceduresScript: Text file of SQL commandsStored Procedure: SQL commands stored in database itselfSPROCs have more capabilities than a scriptBATCHBatch is a logical group of SQL statementsRun-time error will halt execution only of FURTHER stepsCan break up multiple steps using GONot available in all toolsGO causes editing tool to send statements to that point for executionGO isnt sent to SQL ServerFormat of SPROCsCREATE PROCEDURE ASEXECUTEEXEC(cute) statementOREXEC(cute) stored procedure nameStatement or sproc runs in its own scopeCant share variables directlyUsers security rules applyCant be used in User Defined Function (UDF)Uses of Stored ProceduresFor returning data (select)For editing dataFor calculationsParametersMethod for sending data into and from a stored procedureINPUT parameters are values sent inOUTPUT parameters are values returnedMust have a holding space (variable) for the returned dataDefined before start of procedure (AS)Declaring ParametersInclude name and datatypeDefault value is optionalWithout a default value, parameter is requiredDirection is optional (input is default)An output parameter must have direction specifiedSample Input ParameterCREATE PROC upFindStudent@SID char(9)ASSELECT * FROM PersonsWhere SchoolID=@SIDSample Output ParameterCREATE PROC upFindStudentID@First varchar(25),@Last varchar(35),@SID char(9) OUTPUTASSELECT @SID=SchoolIDFROM Students_TWhere @First=Firstname and @Last=LastnameReturn ValuesResult of stored procedure indicates success or failureNon-zero value indicates a problemMust be an integerDifferent from an output parameterOutput parameter is about dataRETURN Causes immediate exit VariablesCreate using DECLARENeed to start with @Can use SQL data types or custom data types

DECLARE @StudentName varchar(50)Variable AssignmentSET is usually used similar to procedural languageSET @Var=value

SELECT is usually used when getting a value from a querySELECT @Var=Sum(PossiblePoints) FROM AssignmentsDecision MakingSQL supports two structures for branching:IFCASEBoth structures are similar to other languages (IF THEN, SELECT CASE) Both structures tend to have specific places where usedIF BlocksIF ELSENo end ifNeed to use Begin/End if have more than one instruction to executeIF StartDate < EndDateBeginEndELSEStored Procedures6/2/201517Simple Case StatementCASESimilar to SELECT CASECompares one value to different casesCASE CategoryWHEN pop_comp THEN Popular ComputingWHEN mod_cook THEN Modern CookingENDSearched CASENo test expressionEach WHEN has a boolean test

CASEWHEN Points >= 90 THEN AWHEN Points < 90 AND Extra > 0THEN AENDLooping (While)Typically used with a CURSORCursor data type allows a table to be stored in memory and each row/field to be accessedBREAK allows early exit from loopCONTINUE forces control to start of loopWorking with sets is preferred over loops (SQL is about sets)Finding Identity ValuesWhen need to find the value used to identify the last row added@@IdentityScope_IdentityIdent_Current@@IdentitySystem variable, created/maintained automaticallyReturns the last identity value used as a result of INSERT or SELECT INTONot limited to current scope; may not get correct valueReturns Null if operation failed or a value wasnt generatedReturns last number created if multiple inserts occur (i.e. SELECT INTO)Scope_Identity()Return the last identity values generated in any table in the current session. Returns values inserted only within the current scopeNot affected by other operations.Ident_Current()Not limited by scope and session;Limited to a specified table (table name specified as an argument value).@@RowcountSystem variable, created/maintained automaticallyNumber of rows returned or affected by the last statement0 (zero) is often used as a logical testIf no records found for where clause, notify system or processErrorsErrors can occur because of SQL statementInvalid syntax, or data typeErrors can also reflect business rulesData doesnt match requirements@@ErrorSystem variable, created/maintained automaticallyValue set after each SQL statement;0 (zero) means statement was successfulNumber other than zero is typically a specific errorCan store value in variable and testStored Procedures276/2/2015Try/CatchSimilar to .Net languagesNeed to include BEGIN/ENDBEGIN TRY

END TRYBEGIN CATCH

END CATCHRaise ErrorUsed to send information to calling programSyntax:RaisError (Message string OR Message ID, Severity, State)Severity