programming sql server 2005

Upload: naga-venkatesh-gogana

Post on 10-Apr-2018

227 views

Category:

Documents


0 download

TRANSCRIPT

  • 8/8/2019 Programming SQL Server 2005

    1/60

    Programming SQL ServerDatabase

  • 8/8/2019 Programming SQL Server 2005

    2/60

    Objectives

    Writing basic Transact SQL Block

    Learn the programming constructs

    Assign values to variables

    Control-of flow statements

    Working with dynamic SQLRAISERROR statement

  • 8/8/2019 Programming SQL Server 2005

    3/60

    Writing Transact SQL Blocks

    Basic Transact SQL Block

    Declare

    Begin

    Begin Try

    --Stmts

    End Try

    Begin Catch--Exception handling code

    End Catch

    End

  • 8/8/2019 Programming SQL Server 2005

    4/60

    Assign Values to variables

    Declaring variables

    Declare @ 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

  • 8/8/2019 Programming SQL Server 2005

    5/60

    Control-Of-Flow statements

    GoTo StatementsIF (SELECT SYSTEM_USER()) = 'payroll

    GOTO calculate_salary

    --other statements

    calculate_salary:

    -- Statements to calculate a salary would appear

    --after the label

    IF StatementIF (@ErrorSaveVariable 0)

    BEGIN

    PRINT 'Errors encountered, rolling back.

    ROLLBACK

    END

    ELSE

    BEGIN

    PRINT 'No Errors encountered, committing.

    COMMIT

    END

  • 8/8/2019 Programming SQL Server 2005

    6/60

    Control-Of-Flow statements

    Case Construct

    Syntax :

    Case Variable / column

    When Value1 Then statements

    When value2 then statements

    elsestatements

    end

    SELECT job = CASE Job

    WHEN RBM THEN

    Regional Business Manager

    WHEN BA THENBusiness Analyst

    ELSE

    Trainees

    END FROM Employee ORDER BY Job

  • 8/8/2019 Programming SQL Server 2005

    7/60

    Control-of-flow statements

    While Statement

    While Begin

    StatementsEnd

    Example

    DECLARE abc CURSOR FORSELECT * FROM Shippers

    OPEN abc

    FETCH NEXT FROM abc

    WHILE (@@FETCH_STATUS = 0)

    FETCH NEXT FROM abc

    CLOSE abc

    DEALLOCATE abc

  • 8/8/2019 Programming SQL Server 2005

    8/60

    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.

  • 8/8/2019 Programming SQL Server 2005

    9/60

    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

  • 8/8/2019 Programming SQL Server 2005

    10/60

    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.

    ExampleWAITFOR DELAY '00:00:02'

    SELECT EmployeeID FROM Northwind.dbo.Employees

    Time_to_execute

    which specifies completion of the WAITFOR statement

    ExampleWAITFOR TIME '22:00'DBCC CHECKALLOC

  • 8/8/2019 Programming SQL Server 2005

    11/60

    RAISERROR

    Returns a user-defined error message and sets a system flag to record thatan error has occurred.

    Syntax

    RAISERROR ( { msg_id | msg_str } { , severity ,

    state } [ , argument [ ,...n ] ] )

    Example

    RAISERROR ('The level for job_id:%d should be between %dand %d.', 16, 1, @@JOB_ID, @@MIN_LVL, @@MAX_LVL)

  • 8/8/2019 Programming SQL Server 2005

    12/60

    SQL Server 2005 Cursors

  • 8/8/2019 Programming SQL Server 2005

    13/60

    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

  • 8/8/2019 Programming SQL Server 2005

    14/60

    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_ONLYSpecifies that FETCH NEXT only can be specified

  • 8/8/2019 Programming SQL Server 2005

    15/60

    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

  • 8/8/2019 Programming SQL Server 2005

    16/60

    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

  • 8/8/2019 Programming SQL Server 2005

    17/60

    Working with Cursors

    CURSOR_ROWS

    Total number of rows fetched by the cursor

    Example

  • 8/8/2019 Programming SQL Server 2005

    18/60

    Working with Cursors

    @@FETCH_STATUS

    Returns the status of the fetched row

    0 success

    -1 fetch statement failes

    -2 row fetched is missing

  • 8/8/2019 Programming SQL Server 2005

    19/60

    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.

  • 8/8/2019 Programming SQL Server 2005

    20/60

    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)

    BEGINFETCH NEXT from @Report

    END

    -- Close and deallocate the cursor from sp_cursor_list.

    CLOSE @Report

    DEALLOCATE @Report

  • 8/8/2019 Programming SQL Server 2005

    21/60

    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'abcFETCH NEXT from @Report

    WHILE (@@FETCH_STATUS =0)

    BEGIN

    FETCH NEXT from @Report

    END

    -- Close and deallocate the cursor from sp_describe_cursor_columns.

    CLOSE @ReportDEALLOCATE @Report

    CLOSE abc

    DEALLOCATE abc

    GO

  • 8/8/2019 Programming SQL Server 2005

    22/60

    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'abcFETCH NEXT from @Report

    WHILE (@@FETCH_STATUS =0)

    BEGIN

    FETCH NEXT from @Report

    END

    -- Close and deallocate the cursor from sp_describe_cursor_columns.

    CLOSE @ReportDEALLOCATE @Report

    CLOSE abc

    DEALLOCATE abc

    GO

  • 8/8/2019 Programming SQL Server 2005

    23/60

    Sp_describe_cursor_tables

    DECLARE abc CURSOR KEYSET FOR SELECT * from employee_5OPEN abcDECLARE @Report CURSOREXEC master.dbo.sp_describe_cursor_tables

    @cursor_return = @Report OUTPUT,@cursor_source = N'global', @cursor_identity = N'abc

    FETCH NEXT from @ReportWHILE (@@FETCH_STATUS -1)BEGIN

    FETCH NEXT from @ReportENDCLOSE @ReportDEALLOCATE @Report

    GOCLOSE abcDEALLOCATE abcGO

  • 8/8/2019 Programming SQL Server 2005

    24/60

    Working with static cursors

    declare c1 cursor for select * from empdeclare @eno int, @ename varchaR(20), @dept intbegin

    open c1fetch next from c1 into @eno, @ename, @deptselect @eno,@ename,@dept

    waitfor delay '00:00:20fetch next from c1 into @eno, @ename, @deptselect @@fetch_status, @eno,@ename,@deptclose c1deallocate c1

    end

    Note : Run the update emp set dept=34 where eno=2 after runing the aboveblock of statements

  • 8/8/2019 Programming SQL Server 2005

    25/60

    Working with dynamic cursors

    declare c1 cursor scroll dynamic for select * from empdeclare @eno int, @ename varchaR(20), @dept intbegin

    open c1fetch next from c1 into @eno, @ename, @deptselect @eno,@ename,@dept

    waitfor delay '00:00:20fetch next from c1 into @eno, @ename, @deptselect @@fetch_status, @eno,@ename,@deptclose c1deallocate c1

    end

    Run the update emp set dept=34 where eno=2 after runing the above

    block of statements

  • 8/8/2019 Programming SQL Server 2005

    26/60

    Working with updateable cursors

    declare c1 cursor scroll dynamic for select * from employee_5 for update of salarydeclare @eno int, @ename varchar(20), @sal intbegin

    open c1fetch next from c1 into @eno,@ename,@salwhile @@fetch_Status=0begin

    if @eno=103beginupdate employee_5 set salary=salary+200 where current of c1break

    endfetch next from c1 into @eno,@ename,@salend

    end

    close c1deallocate c1

  • 8/8/2019 Programming SQL Server 2005

    27/60

    Transact SQL(Procedures and Functions)

  • 8/8/2019 Programming SQL Server 2005

    28/60

    objectives

    Creating procedures

    Stored procedure recompilation

    Encrypting stored procedures

    Return values from stored procedures

  • 8/8/2019 Programming SQL Server 2005

    29/60

    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 }

  • 8/8/2019 Programming SQL Server 2005

    30/60

    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 orderMasterEnd

    Create ProcedureOrderProc;2 As

    Begin Select * from orderTrans End

    Drop procedure OrderProc

  • 8/8/2019 Programming SQL Server 2005

    31/60

    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

    BEGINSET @c1 = CURSOR FORWARD_ONLY STATIC FOR

    SELECT * FROM EMPLOYEE;

    OPEN @C1;

    END

    DECLARE @C2 CURSOR

    EXEC PROC123 @C2 OUTFETCH NEXT FROM @C2

  • 8/8/2019 Programming SQL Server 2005

    32/60

    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

  • 8/8/2019 Programming SQL Server 2005

    33/60

    Create procedure options

    Encryption

    Example

    Sp_helptext pass_check

    The object comments have been encrypted.

  • 8/8/2019 Programming SQL Server 2005

    34/60

    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

  • 8/8/2019 Programming SQL Server 2005

    35/60

    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

  • 8/8/2019 Programming SQL Server 2005

    36/60

    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

  • 8/8/2019 Programming SQL Server 2005

    37/60

    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

  • 8/8/2019 Programming SQL Server 2005

    38/60

    Automatic Execution of SP

    Mark a procedure for automatic execution

    Sp_procOption SPName , True

    UnMarks a procedure from automatic execution

    Sp_procOption SPName , False

  • 8/8/2019 Programming SQL Server 2005

    39/60

    Creating procedures (IN parameter)

    Creating Procedure

    Create procedure myproc(@p1 int IN)

    as

    declare

    begin

    end

    Calling the procedure

    Exec myproc 23

  • 8/8/2019 Programming SQL Server 2005

    40/60

    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

  • 8/8/2019 Programming SQL Server 2005

    41/60

    Default values to stored procedures

    Create procedure (@ type =value,) as

    Example

    CREATE PROCEDURE mytables ( @type char(2)=U)ASSELECT * FROM sysobjects WHERE type = @type contd.,

    GO

    EXECUTE mytablesEXECUTE mytables DEFAULTEXECUTE mytables P

  • 8/8/2019 Programming SQL Server 2005

    42/60

    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

  • 8/8/2019 Programming SQL Server 2005

    43/60

    Default values to stored procedures

    Create procedure (@ type =value,) as

    Example

    CREATE PROCEDURE mytables ( @type char(2)=U)ASSELECT * FROM sysobjects WHERE type = @type contd.,GOEXECUTE mytablesEXECUTE mytables DEFAULTEXECUTE mytables P

  • 8/8/2019 Programming SQL Server 2005

    44/60

    Returning values from stored procedures

    UsingOUT Parameters

    Using CURSOR data type

    Using return keyword

  • 8/8/2019 Programming SQL Server 2005

    45/60

    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

    endCall the SP

    declare @x varchar(40)

    execute @x=myproc

  • 8/8/2019 Programming SQL Server 2005

    46/60

    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

  • 8/8/2019 Programming SQL Server 2005

    47/60

    Parameters with CURSOR data type

    Use CURSOR data types only forOUT 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

  • 8/8/2019 Programming SQL Server 2005

    48/60

    Creating triggers

    Triggers are used to enforce constraints on the tables

    Triggers are automatically called when data in inserted or updated ordeleted for a table

    Sp_helptrigger view triggers for a table

    Sp_helptext view text of a trigger

    Types of triggers

    AFTER

    INSTEAD OF

  • 8/8/2019 Programming SQL Server 2005

    49/60

    Create trigger statement

    Create trigger on for insert | update|deleteasdeclare---begin

    statementsend

  • 8/8/2019 Programming SQL Server 2005

    50/60

    AFTER Triggers

    Apply

    Only to tables

    Executed after

    Constraint processing

    inserted and deleted tables creation

    The triggering action

  • 8/8/2019 Programming SQL Server 2005

    51/60

    INSTEAD OF Triggers

    Applicability

    Tables and Views

    execution

    Before: Constraint processing

    In place of: The triggering action

    After: inserted and deleted tables creation

  • 8/8/2019 Programming SQL Server 2005

    52/60

    Triggers

    Types of triggers

    After Triggers

    InsteadOf Triggers

  • 8/8/2019 Programming SQL Server 2005

    53/60

    After triggers(order of Execution)

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

    Transaction beginsTransaction begins

    Constraints are checkedConstraints are checked

    New Record

    New Record

  • 8/8/2019 Programming SQL Server 2005

    54/60

    After Trigger (Order of execution)

    Create trigger insertCreate trigger insert

    on emp for insert ason emp for insert asbeginbeginselect Row insertedselect Row inserted

    endend

    Trigger FiresTrigger Fires

    If trigger contains aIf trigger contains a rollbackrollback,,Data is not insertedData is not inserted

    If trigger contains doesIf trigger contains does

    not havenot have

    rollbackrollback Data is insertedData is inserted

    (Transaction Ends)

  • 8/8/2019 Programming SQL Server 2005

    55/60

    Instead of triggers

    create trigger ins_on_view_v1 on v1

    instead of insert asdeclare @teno numeric(4), @tename varchar(20), @tdname varchar(20),@tdno numeric(3),@tsal numeric(6)begin

    select @teno=eno,@tename=ename,@tdname=dname from insertedset @tdno=2set @tsal=21000

    insert into employee values(@teno,@tename,@tdno,@tsal)insert into dept values(@tdno,@tdname)select '2 rows inserted...'

    end

  • 8/8/2019 Programming SQL Server 2005

    56/60

    Tables referred inside triggers

    Inserted

    Contains rows that were inserted

    Deleted

    Contains rows that were deleted

    Tables can be referenced only inside triggers

  • 8/8/2019 Programming SQL Server 2005

    57/60

    Functions

    Types of functionsScalar function

    Inline Table valued function

    Scalar Function

    Create function (@parameter type,)

    returns

    as

    declare

    begin

    end

  • 8/8/2019 Programming SQL Server 2005

    58/60

    Functions

    Inline Table valued Function

    Create function (@parameter type,)

    returns table

    [ with encryption ]

    as

    return

    Example

    CREATE FUNCTION fn (@eno int ) RETURNS table AS RETURN ( SELECT *

    FROM emp WHERE empid = @eno )

  • 8/8/2019 Programming SQL Server 2005

    59/60

    Functions

    Create function check (@dt smalldatetime)returns intasdeclare

    begin

    end

  • 8/8/2019 Programming SQL Server 2005

    60/60

    Functions

    Create function emp_det (@ecode numeric(5))returns tableasreturn(select * from emp where eno=@ecode)