Programming SQL Server 2005
Programming SQL Server 2005
Database
Objectives
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
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
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 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
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
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
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 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
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)
New Record
New Record
After Trigger (Order of execution)
(Transaction Ends)
Instead of 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