You are on page 1of 51

Unit 6: Programming with SQL Server

Pratian Technologies (India) Pvt. Ltd.


www.pratian.com

Overview
Variables Flow control constructs
IF THEN ELSE CASE GOTO RETURN WAITFOR WHILE BREAK and CONTINUE

Error Handling Procedures Functions Triggers Cursors


Copyright 2010 Pratian Technologies www.pratian.com

Basic SQL

VARIABLES
You can store a value in a user-defined variable in one statement and then refer to it later in another statement This enables you to pass values from one statement to another User variables are written as @var_name, where the variable name var_name consists of alphanumeric and the special character _

Copyright 2010 Pratian Technologies www.pratian.com

Basic SQL

VARIABLES
Syntax:
DECLARE @varname1, @varname2, ... data type;

For Ex:
DECLARE @Student_Id int; DECLARE @Sname, @Cname varchar(15);

Variable assignment
For variable assignments, use either SET or SELECT SET @Sname = Krishna; SELECT @Sname = Name FROM Students WHERE StudentId = 1001;

Copyright 2010 Pratian Technologies www.pratian.com

Basic SQL

FLOW CONTROL CONSTRUCTS


Flow Control Constructs include the IF, CASE, GOTO, RETURN , WAITFOR, WHILE, BREAK and CONTINUE constructs These constructs can contain single statement or a block of statements using BEGIN..END statement. These constructs can be nested also.

Copyright 2010 Pratian Technologies www.pratian.com

Basic SQL

FLOW CONTROL CONSTRUCTS


IF Statement
Syntax IF search_condition statement_list ELSE IF search_condition statement_list ELSE statement_list

For Ex:
IF @CourseId = 1 SET @Fees = 1000;

Copyright 2010 Pratian Technologies www.pratian.com

Basic SQL

FLOW CONTROL CONSTRUCTS


CASE Statement
Syntax CASE case_value WHEN when_value THEN statement_list [WHEN when_value THEN statement_list] ... [ELSE statement_list] END Or CASE WHEN search_condition THEN statement_list [WHEN search_condition THEN statement_list] ... [ELSE statement_list] END
Copyright 2010 Pratian Technologies www.pratian.com

Basic SQL

FLOW CONTROL CONSTRUCTS


For Ex:
DECLARE @shipping_cost INT; DECLARE @delivery_day INT; SET @delivery_day = DATEPART(day, getdate()); CASE @delivery_day WHEN 1 THEN SET @shipping_cost = 20; WHEN 2 THEN SET @shipping_cost = 15; WHEN 3 THEN SET @shipping_cost = 10; ELSE SET @shipping_cost = 5; END;
Copyright 2010 Pratian Technologies www.pratian.com

Basic SQL

FLOW CONTROL CONSTRUCTS


GOTO Statement Implements a simple code jump construct Is used to jump to a particular line of the code Need to define a label before we use GOTO

Copyright 2010 Pratian Technologies www.pratian.com

Basic SQL

FLOW CONTROL CONSTRUCTS


GOTO Syntax
[label:] statement_list GOTO [label]

For Ex:
DECLARE @day INT; SET @day = 0; WHILE (@day <= 10) BEGIN IF @day = 5 THEN GOTO simple_jump; SET @day = @day + 1; END simple_jump: SELECT Fifth day of the month;

Copyright 2010 Pratian Technologies www.pratian.com

Basic SQL

FLOW CONTROL CONSTRUCTS


RETURN statement When the RETURN key word is encountered, statement execution ends, unconditionally Any lines following a RETURN are not executed
DECLARE @Count int SET @Count = 0 WHILE @Count <= 10 BEGIN IF @Count = 5 BEGIN PRINT Hello World RETURN END SET @Count = @Count + 1 END
Copyright 2010 Pratian Technologies www.pratian.com

Basic SQL

FLOW CONTROL CONSTRUCTS


WAITFOR statement Allows statement execution to be paused for a delayed time amount, or until a specific time of day
DECLARE @Count int SET @Count = 0 WHILE @Count <= 10 BEGIN IF @Count = 5 BEGIN PRINT Hello World WAITFOR DELAY 00:00:02; RETURN END SET @Count = @Count + 1 END
Copyright 2010 Pratian Technologies www.pratian.com

Basic SQL

FLOW CONTROL CONSTRUCTS


WHILE Statement The WHILE Statement repeats the statement_list until the search_condition evaluates to true Syntax:
WHILE search_condition BEGIN statement_list END

Copyright 2010 Pratian Technologies www.pratian.com

Basic SQL

FLOW CONTROL CONSTRUCTS


For Ex:
DECLARE @Count int SET @Count = 0 WHILE @Count < 100 BEGIN PRINT 'Hello World' SET @Count = @Count + 1 END

Copyright 2010 Pratian Technologies www.pratian.com

Basic SQL

FLOW CONTROL CONSTRUCTS


BREAK...CONTINUE BREAK and CONTINUE are used to exit, or continue executing WHILE or IF statements For Ex:
DECLARE @Count int SET @Count = 0 WHILE @Count < 100 BEGIN PRINT 'Hello World' IF @Count = 10 BREAK; ELSE SET @Count = @Count + 1 END Copyright 2010 Pratian Technologies
www.pratian.com

Basic SQL

Question Time
Please try to limit the questions to the topics discussed during the session. Thank you .

Copyright 2010 Pratian Technologies www.pratian.com

Basic SQL

ERROR HANDLING
TRY/CATCH helps to write logic separate the action and error handling code @@ERROR variable lets us know if any error has been generated by the sql statements that have been executed The code meant for the action is enclosed in the TRY block and the code for error handling is enclosed in the CATCH block In case the code within the TRY block fails, the control automatically jumps to the CATCH block
Copyright 2010 Pratian Technologies www.pratian.com

Basic SQL

ERROR HANDLING
Functions to be used in CATCH block are :
ERROR_NUMBER: returns the error number, and is the same value of @@ERROR. ERROR_SEVERITY: returns the severity level of the error that invoked the CATCH block. ERROR_STATE: returns the state number of the error. ERROR_LINE: returns the line number where the error occurred. ERROR_PROCEDURE: returns the name of the stored procedure or trigger for which the error occurred. ERROR_MESSAGE: returns the full message text of the error. The text includes the values supplied for any substitutable parameters, such as lengths, object names, or times

Copyright 2010 Pratian Technologies www.pratian.com

Basic SQL

ERROR HANDLING
Syntax: BEGIN TRY sql_statement | statement_block END TRY BEGIN CATCH sql_statement | statement_block END CATCH

Copyright 2010 Pratian Technologies www.pratian.com

Basic SQL

ERROR HANDLING
Example of TRYCATCH:
BEGIN TRY DECLARE @X INT ---- Divide by zero to generate Error SET @X = 1/0 PRINT 'Command after error in TRY block' END TRY BEGIN CATCH PRINT 'Error Detected' END CATCH PRINT 'Command after TRY/CATCH blocks'

Output
Error Detected Command after TRY/CATCH blocks

Copyright 2010 Pratian Technologies www.pratian.com

Basic SQL

ERROR HANDLING
Another Example of TRYCATCH:
BEGIN TRY -- Generate a divide-by-zero error. SELECT 1/0; END TRY BEGIN CATCH SELECT ERROR_NUMBER() AS ErrorNumber, ERROR_SEVERITY() AS ErrorSeverity, ERROR_STATE() AS ErrorState, ERROR_PROCEDURE() AS ErrorProcedure, ERROR_LINE() AS ErrorLine, ERROR_MESSAGE() AS ErrorMessage; END CATCH; GO

Copyright 2010 Pratian Technologies www.pratian.com

Basic SQL

ERROR HANDLING
Example of TRYCATCH: RAISERROR function
BEGIN TRY DECLARE @MyInt INT; -- Following statement will create Devide by Zero Error SET @MyInt = 1/0; END TRY BEGIN CATCH DECLARE @ErrorMessage NVARCHAR(4000); SELECT @ErrorMessage = ERROR_MESSAGE(); RAISERROR (@ErrorMessage, 16, 1); END CATCH; GO Result: Msg 50000, Level 16, State 1, Line 9 Divide by zero error encountered.

Copyright 2010 Pratian Technologies www.pratian.com

Basic SQL

Question Time
Please try to limit the questions to the topics discussed during the session. Thank you .

Copyright 2010 Pratian Technologies www.pratian.com

Basic SQL

PROCEDURES
Custom programming scripts with embedded SQL statements that are stored in a compiled form and executed directly by the MS SQL server Allow us to store logic [rules] on the database Improves the performance as less information needs to be sent between the server and the client Procedure names can be up to 64 characters long

Copyright 2010 Pratian Technologies www.pratian.com

Basic SQL

PROCEDURES
Advantages of procedures
Faster Execution: Reduced need for data transfer back and forth between a program and the database server.
Note: The use of SPs does not guarantee improved speed as a lot depends on the code inside of the SP

Reduced code redundancy: Similar code needed through out the application can be written once and can be reused. Selects, Inserts, etc.. Maintenance: If there are changes in the underlying database schema, code changes can be localized to a few SPs Security: Direct access to tables by user programs is a problem and with SPs, data access can be monitored, and logged if necessary. Centralized security rules can be applied
Copyright 2010 Pratian Technologies www.pratian.com

Basic SQL

PROCEDURES
Syntax:
CREATE PROCEDURE proc_name [proc_parameter data_type[......]] AS BEGIN routine_body here; END proc_name : procedure name proc_parameter : [default | OUTPUT ] param_name type data_type : any valid data type of Sql server routine_body : Valid SQL procedure statement

Copyright 2010 Pratian Technologies www.pratian.com

Basic SQL

PROCEDURES
If you don't specify IN, OUTPUT for the parameter, it will default to IN An IN parameter is passed into the stored procedure to use internally An OUTPUT parameter is set within the procedure, but accessed by the caller The name and data type of the parameter are used in the stored procedure for referencing and setting values going in and out of the procedure The data type can be any valid data type for MS SQL

Copyright 2010 Pratian Technologies www.pratian.com

Basic SQL

PROCEDURES
For Ex: Without parameters
CREATE PROCEDURE GetStudents AS BEGIN SELECT * FROM Students END

With IN Parameter
CREATE PROCEDURE GetFeesForStudent @StudentId INT AS BEGIN SELECT Fees FROM Students WHERE StudentId = @StudentId END
Copyright 2010 Pratian Technologies www.pratian.com

Basic SQL

PROCEDURES
With IN and OUT parameters
CREATE PROCEDURE GetFeesForStudent @StudentId INT, @TotalFees INT OUTPUT AS BEGIN SELECT @TotalFees = Fees FROM Students WHERE StudentId = @StudentId END

Method to invoke a procedure


EXEC GetStudents; EXEC GetFeesForStudent 1001; EXEC GetFeesForStudent 1001, @TotalFees;
Copyright 2010 Pratian Technologies www.pratian.com

Basic SQL

PROCEDURES
ALTER PROCEDURE

A procedure can be altered once created Syntax:


ALTER PROCEDURE proc_name [proc_parameter data_type[......]] AS BEGIN routine_body here; END

proc_name : procedure name proc_parameter : [ default | OUT ] param_name type data_type : any valid data type of Sql server routine_body : Valid SQL procedure statement
DROP PROCDURE DROP PROCEDURE procedure_name
Copyright 2010 Pratian Technologies www.pratian.com

Basic SQL

USER DEFINED FUNCTIONS - UDFs


User Defined Functions are compact pieces of Transact SQL code, which can accept parameters, and return either a value, or a table Acts like a function in programming language. Can be parameterized and called any number of times Simpler to invoke than Stored Procedures from inside another SQL statement Three types of UDFs
Scalar UDFs Inline Table valued UDFs Multi-statement table valued UDFs
Copyright 2010 Pratian Technologies www.pratian.com

Basic SQL

USER DEFINED FUNCTIONS - UDFs


Scalar UDF
Returns scalar data type Text, ntext, image, timestamp are not supported

Scalar UDFs have the following syntax:


CREATE FUNCTION owner.function_name (parameter_name data_type [=default] [, n]) RETURNS scalar_data_type [WITH function_option] AS BEGIN Function_body RETURN scalar_expression END

Copyright 2010 Pratian Technologies www.pratian.com

Basic SQL

USER DEFINED FUNCTIONS - UDFs


Scalar UDFs
Example

Copyright 2010 Pratian Technologies www.pratian.com

Basic SQL

USER DEFINED FUNCTIONS - UDFs


Inline Table Valued UDFs
An Inline Table-Value user-defined function returns a table data type. Its an alternative to a view as the user-defined function can pass parameters into a T-SQL select command Provides us with a parameterized, non-updateable view of the underlying tables

Syntax:
CREATE FUNCTION owner.function_name (parameter_name data_type [=default] [, n]) RETURNS TABLE [WITH function_option] AS RETURN ( SELECT_statement )
Copyright 2010 Pratian Technologies www.pratian.com

Basic SQL

USER DEFINED FUNCTIONS - UDFs


Inline table valued UDFs Example:

Copyright 2010 Pratian Technologies www.pratian.com

Basic SQL

USER DEFINED FUNCTIONS - UDFs


Multi-statement table valued UDFs
A Multi-Statement Table-Value user-defined function returns a table and is also an exceptional alternative to a view The ability to pass parameters into a T-SQL select command or a group of them gives us the capability to create a parameterized, non-updateable view of the data in the underlying tables Within the create function command you must define the table structure that is being returned After creating this type of user-defined function, you can use it in the FROM clause of a T-SQL command

Copyright 2010 Pratian Technologies www.pratian.com

Basic SQL

USER DEFINED FUNCTIONS - UDFs


Syntax:
CREATE FUNCTION owner.function_name ((parameter_name data_type [=default] [, n]) RETURNS @table_variable_name TABLE (table_definition) [WITH function_option] AS BEGIN Function_body RETURN END

Copyright 2010 Pratian Technologies www.pratian.com

Basic SQL

USER DEFINED FUNCTIONS - UDFs


Example

Copyright 2010 Pratian Technologies www.pratian.com

Basic SQL

USER DEFINED FUNCTIONS - UDFs


Limitations of UDFs
UDF Prohibit Usage of Non-Deterministic Built-in Functions. However it is allowed in SQL Server 2008. UDF cannot Call Stored Procedure UDF have only access to Extended Stored Procedure. UDFs cannot make use of dynamic SQL or temporary tables within the code. Table variables are allowed though. UDF can not Return XML. UDF does not support SET options. UDF does not Support Error Handling TRY/CATCH,RAISEERROR or @@ERROR are not allowed in UDFs. UDF is not allowed to modify the physical state of a database using INSERT, UPDATE or DELETE statements. A UDF (any of the three variations - scalar, inline or multistatement) cannot be used to return multiple result sets.

Copyright 2010 Pratian Technologies www.pratian.com

Basic SQL

USER DEFINED FUNCTIONS - UDFs


ALTER FUNCTION
UDFs can be modified using the ALTER FUNCTION statement. The syntax of this statement is identical to CREATE FUNCTION, with the exception of using the ALTER keyword instead of CREATE.

DROP FUNCTION
DROP FUNCTION function_owner.function_name; Example: DROP FUNCTION dbo.GetCustomersByCountry

Copyright 2010 Pratian Technologies www.pratian.com

Basic SQL

TRIGGERS
A trigger is a database object that is attached to a table. Is attached to a table and is only fired when an INSERT, UPDATE or DELETE occurs Guards against malicious inserts and updates. Triggers are used to enforce data integrity and business rules

Copyright 2010 Pratian Technologies www.pratian.com

Basic SQL

TRIGGERS
Syntax: CREATE TRIGGER [owner.]trigger_name ON[owner.] table_name FOR[INSERT/UPDATE/DELETE] AS IF UPDATE (column_name) [{AND/OR} UPDATE(COLUMN_NAME)...] { sql_statements }

Copyright 2010 Pratian Technologies www.pratian.com

Basic SQL

TRIGGERS
For Ex: [To insert default CourseId after student insert].
CREATE TRIGGER dbo.ins_trig ON Students AFTER INSERT AS INSERT INTO StudentCourses (StudentId, VALUES (inserted.StudentId, 1)

CourseId)

INSERT INTO Students (StudentId, Name, Fees, JoinDate) VALUES (1004, Krishna Kumar S, 1000, 2010-12-05)

Copyright 2010 Pratian Technologies www.pratian.com

Basic SQL

TRIGGERS
INSERT Trigger
When an INSERT trigger statement is executed, new rows are added to the trigger table and to the inserted table at the same time. The inserted table is a logical table that holds a copy of rows that have been inserted. The inserted table can be examined by the trigger to determine whether or how the trigger action are carried out. With the inserted table, inserted data can be referenced without having to store the information to the variables.

Copyright 2010 Pratian Technologies www.pratian.com

Basic SQL

TRIGGERS
DELETE Trigger
Rows are deleted from the table and are placed in a special table called deleted table

UPDATE Trigger
The original rows are moved into deleted table Updated row is inserted into inserted table and the table is being updated

Copyright 2010 Pratian Technologies www.pratian.com

Basic SQL

TRIGGERS
ALTER trigger
Triggers once created can be altered Syntax would be the same as in CREATE Instead of CREATE, we need to use ALTER

To delete a trigger from the database


DROP TRIGGER trigger_name;

Copyright 2010 Pratian Technologies www.pratian.com

Basic SQL

CURSORS
Cursors are used when the SQL Select statement is expected to return more than one row Is a database object used by applications to manipulate data in a set on a row-by-row basis Cursors are functions supported inside procedures and

Way to use cursor


Before using a cursor, it must be declared and its definition contains the query Then we have to open the cursor and fetch from it After finishing the task, we should close the cursor and de-allocate it Copyright 2010 Pratian Technologies Basic SQL
www.pratian.com

CURSORS
Syntax:
DECLARE <cursor_name> CURSOR FOR <select_statement> OPEN <cursor_name> FETCH FROM <cursor_name> INTO <@var1>,<@var2> CLOSE <cursor_name> DEALLOCATE <cursor_name>

Copyright 2010 Pratian Technologies www.pratian.com

Basic SQL

CURSORS
For EX:
DECLARE @StudentId INT DECLARE StudentCursor CURSOR LOCAL FOR SELECT StudentId From Students OPEN StudentCursor FETCH NEXT FROM StudentCursor INTO @StudentId
/* READ FIRST RECORD */

WHILE @@FETCH_STATUS = 0 /* LOOP WHILE NO MORE RECORDS */ BEGIN INSERT INTO StudentCourses (StudentId, CourseId) VALUES (@StudentId, 1); FETCH NEXT FROM StudentCursor INTO @StudentId
/* READ NEXT RECORD */

END CLOSE StudentCursor DEALLOCATE StudentCursor

Copyright 2010 Pratian Technologies www.pratian.com

Basic SQL

CURSORS
Guidelines
Try to avoid cursors whenever possible Performance issues Do not forget to CLOSE cursor Do not forget to DEALLOCATE cursor once all tasks are finished Keep the number of rows and columns in a cursor to a minimum Try to use READ ONLY cursors whenever possible

Copyright 2010 Pratian Technologies www.pratian.com

Basic SQL

Question Time
Please try to limit the questions to the topics discussed during the session. Thank you .

Copyright 2010 Pratian Technologies www.pratian.com

Basic SQL