Programming SQL Server Database

Objectives

Writing basic Transact SQL Block Learn the programming constructs Assign values to variables Control-of flow statements Working with dynamic SQL RAISERROR statement

Writing Transact SQL Blocks

Basic Transact SQL Block
Declare <variable declarations> Begin Begin Try --Stmts End Try Begin Catch --Exception handling code End Catch End

Assign Values to variables Declaring variables Declare @<variable> DataType Cannot initialize variables during declaration Example Declare @t int Assign Values to variables  Use ´selectµ keyword Example ‡Select @t = 10 ‡Select @t = max(basic) from employee Use ´setµ keyword Example .

rolling back.µ COMMIT END .Control-Of-Flow statements GoTo Statements IF (SELECT SYSTEM_USER()) = 'payrollµ GOTO calculate_salary --other statements calculate_salary: -. committing.µ ROLLBACK END ELSE BEGIN PRINT 'No Errors encountered.Statements to calculate a salary would appear --after the label IF Statement IF (@ErrorSaveVariable <> 0) BEGIN PRINT 'Errors encountered.

Control-Of-Flow statements Case Construct Syntax : Case Variable / column When Value1 Then statements When value2 then statements else statements end SELECT job = CASE Job WHEN ¶RBM· THEN ¶Regional Business Manager· WHEN ¶BA· THEN ¶Business Analyst· ELSE ¶Trainees· END FROM Employee ORDER BY Job .

Control-of-flow statements ´Whileµ Statement While <condition> Begin Statements End Example DECLARE abc CURSOR FOR SELECT * FROM Shippers OPEN abc FETCH NEXT FROM abc WHILE (@@FETCH_STATUS = 0) FETCH NEXT FROM abc CLOSE abc DEALLOCATE abc .

or procedure. or batch. stored procedure. If no value is specified on RETURN. When used in a stored procedure can specify an integer value to return to the calling application.Control-of-flow statements ´Returnµ statement Unconditionally terminates a query. . a stored procedure returns the value 0. batch. None of the statements in a stored procedure or batch following the RETURN statement are executed.

INT OUTPUT AS @MaxQuantity DECLARE @ErrorSave INT SET @ErrorSave = 0 SELECT FirstName.Control-of-flow statements CREATE PROCEDURE SampleProcedure @EmployeeIDParm INT. Title FROM Employees WHERE EmployeeID = @EmployeeIDParm SELECT @MaxQuantity = MAX(Quantity) FROM [Order Details] IF (@@ERROR <> 0) SET @ErrorSave = @@ERROR RETURN @ErrorSave . LastName.

dbo.Control-of-flow statements The WAITFOR statement suspends the execution of a connection until either: A specified time interval has passed. The WAITFOR statement is specified with one of two clauses: amount_of_time_to_pass before Time to wait can be up to 24 hours. Example WAITFOR DELAY '00:00:02' SELECT EmployeeID FROM Northwind. A specified time of day is reached.Employees Time_to_execute  which specifies completion of the WAITFOR statement Example WAITFOR TIME '22:00' DBCC CHECKALLOC .

argument [ .. @@MAX_LVL) .RAISERROR Returns a user-defined error message and sets a system flag to record that an error has occurred. @@MIN_LVL. @@JOB_ID. state } [ . 16. 1.n ] ] ) Example RAISERROR ('The level for job_id:%d should be between %d and %d.. severity ..'. Syntax RAISERROR ( { msg_id | msg_str } { .

SQL Server 2005 Cursors .

Working with Cursors Declaring a Cursor Declare cursorname cursor« Opening a cursor Open cursorName Fetching rows from the cursor Fetch first | next | last | prior from cursor [ into variables ] Closing a cursor Close cursorName Deallocating a cursor Deallocate cursorName .

Working with Cursors DECLARE cursor_name CURSOR [ LOCAL | GLOBAL ] [ FORWARD_ONLY | SCROLL ] [ STATIC | KEYSET | DYNAMIC | FAST_FORWARD ] [ READ_ONLY ] FOR select_statement [ FOR UPDATE [ OF column_name [ ...n ] ] ] Local Scope of the cursor is local to that batch or stored procedure Global Scope of the cursor is global to the connection FORWARD_ONLY Specifies that FETCH NEXT only can be specified ..

Working with Cursors STATIC Cursor makes a temporary copy of the database data in temporary tables in tempdb KEYSET Updates and deletes made by other users are visible Inserts made into the table is not visible DYNAMIC Changes are visible as the user scrolls through the cursor FAST_FORWARD Declares a FORWARD_ONLY and READ_ONLY cursor .

Working with Cursors READ_ONLY Creates a read only cursor Opening a cursor Open CursorName Fetching rows from a cursor Fetch First | Next | Last | Prior | Absolute N @v1. @v2« from CursorName into Closing a Cursor Close CursorName .

Working with Cursors

CURSOR_ROWS
Total number of rows fetched by the cursor Example

Working with Cursors

@@FETCH_STATUS
Returns the status of the fetched row 

0 success -1 fetch statement failes -2 row fetched is missing

cursors

sp_cursor_list
Returns a list of cursors currently visible on the connection and their attributes.

sp_describe_cursor
Describes the attributes of a cursor, such as whether it is a forward-only or scrolling cursor.

sp_describe_cursor_columns
Describes the attributes of the columns in the cursor result set.

sp_describe_cursor_tables
Describes the base tables accessed by the cursor.

DECLARE @Report CURSOR -. EXEC master.Declare a cursor variable to hold the cursor output variable -.sp_cursor_list @cursor_return = @Report OUTPUT.dbo.Sp_cursor_list -.from sp_cursor_list.Declare a cursor DECLARE abc CURSOR for select * from employee_5 OPEN abc -. CLOSE @Report DEALLOCATE @Report . FETCH NEXT from @Report WHILE (@@FETCH_STATUS <> -1) BEGIN FETCH NEXT from @Report END -.Fetch all the rows from the sp_cursor_list output cursor.Close and deallocate the cursor from sp_cursor_list.Execute sp_cursor_list into the cursor variable.@cursor_scope = 2 -.

Close and deallocate the cursor from sp_describe_cursor_columns. @cursor_identity = N'abc¶ FETCH NEXT from @Report WHILE (@@FETCH_STATUS =0) BEGIN FETCH NEXT from @Report END -.Declare and open a global cursor.sp_describe_cursor_columns @cursor_return = @Report OUTPUT. CLOSE @Report DEALLOCATE @Report CLOSE abc DEALLOCATE abc GO . DECLARE abc CURSOR KEYSET FOR SELECT ename from employee_5 OPEN abc DECLARE @Report CURSOR EXEC master.Sp_describe_cursor_columns -.dbo. @cursor_source = N'global'.

@cursor_identity = N'abc¶ FETCH NEXT from @Report WHILE (@@FETCH_STATUS =0) BEGIN FETCH NEXT from @Report END -. DECLARE abc CURSOR FOR SELECT ename from employee_5 OPEN abc DECLARE @Report CURSOR EXEC master. CLOSE @Report DEALLOCATE @Report CLOSE abc DEALLOCATE abc GO .Declare and open a global cursor.Close and deallocate the cursor from sp_describe_cursor_columns.dbo. @cursor_source = N'global'.Sp_describe_cursor_columns -.sp_describe_cursor_columns @cursor_return = @Report OUTPUT.

@cursor_source = N'global'. @cursor_identity = N'abc¶ FETCH NEXT from @Report WHILE (@@FETCH_STATUS <> -1) BEGIN FETCH NEXT from @Report END CLOSE @Report DEALLOCATE @Report GO CLOSE abc DEALLOCATE abc GO .sp_describe_cursor_tables @cursor_return = @Report OUTPUT.dbo.Sp_describe_cursor_tables DECLARE abc CURSOR KEYSET FOR SELECT * from employee_5 OPEN abc DECLARE @Report CURSOR EXEC master.

@ename. @ename varchaR(20).@dept close c1 deallocate c1 end Note : Run the ´update emp set dept=34 where eno=2 after runing the above block of statements .@ename. @eno.@ename. @dept select @eno. @dept select @@fetch_status.Working with static cursors declare c1 cursor for select * from emp declare @eno int.@dept waitfor delay '00:00:20¶ fetch next from c1 into @eno. @ename. @dept int begin open c1 fetch next from c1 into @eno.

@eno. @dept select @eno. @ename.@dept close c1 deallocate c1 end Run the ´update emp set dept=34 where eno=2 after runing the above block of statements . @dept select @@fetch_status.Working with dynamic cursors declare c1 cursor scroll dynamic for select * from emp declare @eno int. @ename varchaR(20). @dept int begin open c1 fetch next from c1 into @eno.@ename. @ename.@ename.@dept waitfor delay '00:00:20¶ fetch next from c1 into @eno.

@ename varchar(20).@ename. @sal int begin open c1 fetch next from c1 into @eno.@sal end end close c1 deallocate c1 .Working with updateable cursors declare c1 cursor scroll dynamic for select * from employee_5 for update of salary declare @eno int.@ename.@sal while @@fetch_Status=0 begin if @eno=103 begin update employee_5 set salary=salary+200 where current of c1 break end fetch next from c1 into @eno.

Transact SQL (Procedures and Functions) .

objectives Creating procedures Stored procedure recompilation Encrypting stored procedures Return values from stored procedures .

Class...Method } .Creating Stored procedures Create procedure [schema.] procedure_name[.N) [With Encryption | Recompile | Execute_As_Clause ] As { T-SQL block | External name Assembly..no] (@parameter datatype [Varying ][=default] [OUT].

1 As Begin select * from orderMaster End Create Procedure OrderProc.Create procedure No Is an optional number Used to group the Stored procedure Grouped procedure can be dropped together Example Create procedure OrderProc.2 As Begin Select * from orderTrans End Drop procedure OrderProc .

OPEN @C1.Create Procedure Options VARYING Specifies that the resultset is an output parameter Applies only to cursor parameters Example CREATE PROCEDURE proc123 @c1 CURSOR VARYING OUTPUT AS BEGIN SET @c1 = CURSOR FORWARD_ONLY STATIC FOR SELECT * FROM EMPLOYEE. END DECLARE @C2 CURSOR EXEC PROC123 @C2 OUT FETCH NEXT FROM @C2 .

code of the SP end .Create procedure options Encryption Converts the text of the SP into obfuscated form Output of obfuscation not directly visible in any catalog views Option not valid for CLR procedures Example create procedure pass_check (@pwd varchar(20)) With encryption As begin .

.Create procedure options Encryption Example Sp_helptext pass_check The object comments have been encrypted.

Create procedure Options Recompile Plan of the SP is not cached Not specified for CLR procedures To discard plans for individual queries« Use RECOMPILE as the Query hint .

NET assembly The assembly would be referenced from a CLR procedure Example Create procedure p1 (@x int) as External name Emp.GetDetails .Emp.Create procedure options External Name clause Used to specify the name of the .

sysobjects where xtype='p'and name='myproc') View information about dependencies select * from sys.Getting information about procedures View information about TSQL SPs select * from sys.assembly_modules .sql_modules where object_id=(select id from sys.sql_dependencies View information about CLR modules select * from sys.sql_modules select definition from sys.

Automatic Execution of SP Procedures can be marked for automatic execution Every time when SQL Server 2005 starts Operates under the same permission as members of sysadmin fixed role Error message generated by such SP is written to SQL Server error log .

Automatic Execution of SP Mark a procedure for automatic execution Sp_procOption ¶SPName· . ¶True· UnMarks a procedure from automatic execution Sp_procOption ¶SPName· . ¶False· .

Creating procedures (IN parameter) Creating Procedure Create procedure myproc(@p1 int IN) as declare « begin « end Calling the procedure Exec myproc 23 .

@b int OUT) as begin set @b=@a+10 end Calling procedure Declare @t int EXEC P1 20.Creating procedures (OUT parameter) Creating procedure Create procedure p1(@a int.@t OUT Select @t .

.Default values to stored procedures Create procedure <name> (@<parameter> type =value.«) as « Example CREATE PROCEDURE mytables ( @type char(2)=¶U·) AS SELECT * FROM sysobjects WHERE type = @type contd. GO EXECUTE mytables EXECUTE mytables DEFAULT EXECUTE mytables ¶P· .

@b int OUT) as begin set @b=@a+10 end Calling procedure Declare @t int EXEC P1 20.@t OUT Select @t .Creating procedures (OUT parameter) Creating procedure Create procedure p1(@a int.

GO EXECUTE mytables EXECUTE mytables DEFAULT EXECUTE mytables ¶P· .«) as « Example CREATE PROCEDURE mytables ( @type char(2)=¶U·) AS SELECT * FROM sysobjects WHERE type = @type contd.Default values to stored procedures Create procedure <name> (@<parameter> type =value..

Returning values from stored procedures Using OUT Parameters Using CURSOR data type Using return keyword .

Returning values from SPs Create the SP alter procedure myproc as declare @nm varchar(20) begin select @nm=ename from employee_5 where eno=101 return @nm end Call the SP declare @x varchar(40) execute @x=myproc .

Parameters with CURSOR data type SP with CURSOR parameter CREATE PROCEDURE proc123 @c1 CURSOR VARYING OUTPUT AS SET @c1 = CURSOR FORWARD_ONLY STATIC FOR SELECT * FROM EMPLOYEE OPEN @C1 GO DECLARE @C2 CURSOR EXEC PROC123 @C2 OUT FETCH NEXT FROM @C2 .

Parameters with CURSOR data type Use CURSOR data types only for OUT parameters Varying and OUTPUT clause is compulsory Forward only CURSOR Returns rows at and beyond the cursor position Scrollable CURSOR All rows returned to the calling batch Cursor position is left at the position of the last fetch .

Creating triggers Triggers are used to enforce constraints on the tables Triggers are automatically called when data in inserted or updated or deleted for a table Sp_helptrigger view triggers for a table Sp_helptext view text of a trigger Types of triggers AFTER INSTEAD OF .

´Create trigger«µ statement Create trigger <trigger name> on <table> for insert | update|delete as declare --begin statements end .

AFTER Triggers Apply Only to tables Executed after Constraint processing inserted and deleted tables creation The triggering action .

INSTEAD OF« Triggers Applicability Tables and Views execution Before: Constraint processing In place of: The triggering action After: inserted and deleted tables creation .

Triggers Types of triggers After Triggers Instead Of Triggers .

14000) Transaction begins Constraints are checked New Record New Record .·Hyden·.After triggers(order of Execution) Insert into table values(1003.

After Trigger (Order of execution) Create trigger insert Trigger Fires on emp for insert as begin select ´Row insertedµ end If trigger contains a rollback. Data is not inserted If trigger contains does not have rollback Data is inserted (Transaction Ends) . rollback.

Instead of triggers create trigger ins_on_view_v1 on v1 instead of insert as declare @teno numeric(4).@tdno.@tsal) insert into dept values(@tdno. @tdname varchar(20).@tdname) select '2 rows inserted. @tename=ename.' end ..@tename.. @tename varchar(20). @tsal numeric(6) begin select @teno=eno.@tdname=dname from inserted set @tdno=2 set @tsal=21000 insert into employee values (@teno.@tdno numeric(3).

Tables referred inside triggers Inserted Contains rows that were inserted Deleted Contains rows that were deleted Tables can be referenced only inside triggers .

«) returns <datatype> as declare « begin « end .Functions Types of functions Scalar function Inline Table valued function Scalar Function Create function <name>(@parameter type.

«) returns table [ with encryption ] as return <statements> Example CREATE FUNCTION fn (@eno int ) RETURNS table AS RETURN ( SELECT * FROM emp WHERE empid = @eno ) .Functions Inline Table valued Function Create function <name> (@parameter type.

Functions Create function check (@dt smalldatetime) returns int as declare « begin « end .

Functions Create function emp_det (@ecode numeric(5)) returns table as return (select * from emp where eno=@ecode) .