0% found this document useful (0 votes)
129 views

Programming SQL Server 2005

This document provides an overview of programming with SQL Server, including writing Transact SQL blocks, assigning values to variables, control flow statements like IF/CASE/WHILE, working with cursors and dynamic SQL, and using the RAISERROR statement. Key topics covered include declaring variables, assigning values, control structures like IF/CASE/WHILE, opening/fetching/closing cursors, stored procedures, and raising user-defined errors.
Copyright
© Attribution Non-Commercial (BY-NC)
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
129 views

Programming SQL Server 2005

This document provides an overview of programming with SQL Server, including writing Transact SQL blocks, assigning values to variables, control flow statements like IF/CASE/WHILE, working with cursors and dynamic SQL, and using the RAISERROR statement. Key topics covered include declaring variables, assigning values, control structures like IF/CASE/WHILE, opening/fetching/closing cursors, stored procedures, and raising user-defined errors.
Copyright
© Attribution Non-Commercial (BY-NC)
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
You are on page 1/ 60

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
Control-Of-Flow statements

GoTo Statements
 IF (SELECT SYSTEM_USER()) = 'payroll‘
GOTO calculate_salary
--other statements
calculate_salary:
-- Statements to calculate a salary would appear
--after the label

IF Statement
 IF (@ErrorSaveVariable <> 0)
BEGIN
PRINT 'Errors encountered, rolling back.‘
ROLLBACK
END
ELSE
BEGIN
PRINT 'No Errors encountered, committing.‘
COMMIT
END
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
Control-of-flow statements

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

CREATE PROCEDURE SampleProcedure @EmployeeIDParm INT, @MaxQuantity


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

The WAITFOR statement suspends the execution of a connection until either:


 A specified time interval has passed.
 A specified time of day is reached.

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.dbo.Employees
 Time_to_execute
 which specifies completion of the WAITFOR statement
Example
WAITFOR TIME '22:00'
DBCC CHECKALLOC
RAISERROR

Returns a user-defined error message and sets a system flag to record that an
error has occurred.
 Syntax
RAISERROR ( { msg_id | msg_str } { , severity ,
state } [ , argument [ ,...n ] ] )
Example
RAISERROR ('The level for job_id:%d should be between %d
and %d.', 16, 1, @@JOB_ID, @@MIN_LVL, @@MAX_LVL)
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 from CursorName into @v1, @v2…
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.
Sp_cursor_list

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

-- Declare and open a global cursor.


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

-- Declare and open a global cursor.


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

DECLARE abc CURSOR KEYSET FOR SELECT * from employee_5


OPEN abc
DECLARE @Report CURSOR
EXEC master.dbo.sp_describe_cursor_tables
@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
Working with static cursors

declare c1 cursor for select * from emp


declare @eno int, @ename varchaR(20), @dept int
begin
open c1
fetch next from c1 into @eno, @ename, @dept
select @eno,@ename,@dept
waitfor delay '00:00:20‘
fetch next from c1 into @eno, @ename, @dept
select @@fetch_status, @eno,@ename,@dept
close c1
deallocate c1
end
Note : Run the “update emp set dept=34 where eno=2 after runing the above
block of statements
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, @dept
select @eno,@ename,@dept
waitfor delay '00:00:20‘
fetch next from c1 into @eno, @ename, @dept
select @@fetch_status, @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
Working with updateable cursors

declare c1 cursor scroll dynamic for select * from employee_5 for update of salary
declare @eno int, @ename varchar(20), @sal int
begin
open c1
fetch next from c1 into @eno,@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,@ename,@sal
end
end
close c1
deallocate c1
Transact SQL
(Procedures and Functions)
objectives

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

Create procedure [schema.] procedure_name[;no]

(@parameter datatype [Varying ][=default] [OUT],...N)

[With Encryption | Recompile | Execute_As_Clause ]


As
{ T-SQL block | External name Assembly.Class.Method }
Create procedure

No
 Is an optional number
 Used to group the Stored procedure
 Grouped procedure can be dropped together
 Example
Create procedure OrderProc;1 As
Begin select * from orderMaster End
Create Procedure OrderProc;2 As
Begin Select * from orderTrans End
Drop procedure OrderProc
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;
OPEN @C1;
END
DECLARE @C2 CURSOR
EXEC PROC123 @C2 OUT
FETCH NEXT FROM @C2
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
- code of the SP
end
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
Create procedure options

External Name clause


 Used to specify the name of the .NET assembly
 The assembly would be referenced from a CLR procedure
Example
 Create procedure p1 (@x int) as
External name Emp.Emp.GetDetails
Getting information about procedures

View information about TSQL SPs


 select * from sys.sql_modules
 select definition from sys.sql_modules
where object_id=(select id from sys.sysobjects
where xtype='p'and name='myproc')
View information about dependencies
 select * from sys.sql_dependencies

View information about CLR modules


 select * from sys.assembly_modules
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
Creating procedures (OUT parameter)

Creating procedure
 Create procedure p1(@a int, @b int OUT) as
begin
set @b=@a+10
end
Calling procedure
 Declare @t int
EXEC P1 20,@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’
Creating procedures (OUT parameter)

Creating procedure
 Create procedure p1(@a int, @b int OUT) as
begin
set @b=@a+10
end
Calling procedure
 Declare @t int
EXEC P1 20,@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’
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
After triggers(order of Execution)

Insert into table values(1003,’Hyden’,14000)


 Transaction begins
 Constraints are checked

New Record

New Record
After Trigger (Order of execution)

Create trigger insert


on emp for insert as
Trigger Fires 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)
Instead of triggers

create trigger ins_on_view_v1 on v1


instead of insert as
declare @teno numeric(4), @tename varchar(20), @tdname varchar(20),@tdno numeric(3), @tsal
numeric(6)
begin
select @teno=eno,
@tename=ename,@tdname=dname from inserted
set @tdno=2
set @tsal=21000
insert into employee values
(@teno,@tename,@tdno,@tsal)
insert into dept values(@tdno,@tdname)
select '2 rows inserted...'
end
Tables referred inside triggers

Inserted
 Contains rows that were inserted
Deleted
 Contains rows that were deleted
Tables can be referenced only inside triggers
Functions

Types of functions
 Scalar function
 Inline Table valued function
Scalar Function
 Create function <name>(@parameter type,…)
returns <datatype>
as
declare

begin

end
Functions

Inline Table valued 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

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)

You might also like