unit6 programming with sql server.pdf

Upload: divyasindhuri

Post on 08-Aug-2018

243 views

Category:

Documents


0 download

TRANSCRIPT

  • 8/22/2019 Unit6 Programming With SQL Server.pdf

    1/51

    Unit 6:Programming with SQL

    Server

    Pratian Technologies (India) Pvt. Ltd.www.pratian.com

  • 8/22/2019 Unit6 Programming With SQL Server.pdf

    2/51

    Overview

    Variables

    Flow control constructs

    IF THEN ELSE

    CASE GOTO

    RETURN

    WAITFOR

    Basic SQLCopyright 2010 Pratian Technologieswww.pratian.com

    WHILE BREAK and CONTINUE

    Error Handling

    Procedures Functions

    Triggers

    Cursors

  • 8/22/2019 Unit6 Programming With SQL Server.pdf

    3/51

    VARIABLES

    You can store a value in a user-defined variable inone statement and then refer to it later in anotherstatement

    This enables you to pass values from one statementto another

    Basic SQLCopyright 2010 Pratian Technologieswww.pratian.com

    User variables are written as @var_name, where thevariable name var_name consists of alphanumericand the special character _

  • 8/22/2019 Unit6 Programming With SQL Server.pdf

    4/51

    VARIABLES

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

    For Ex: DECLARE @Student_Id int;

    DECLARE @Sname, @Cname varchar(15);

    Basic SQLCopyright 2010 Pratian Technologieswww.pratian.com

    Variable assignment For variable assignments, use either SETor SELECT

    SET @Sname = Krishna;

    SELECT @Sname = Name FROM Students

    WHERE StudentId = 1001;

  • 8/22/2019 Unit6 Programming With SQL Server.pdf

    5/51

    FLOW CONTROL CONSTRUCTS

    Flow Control Constructs include the IF, CASE,GOTO, RETURN , WAITFOR, WHILE, BREAK andCONTINUE constructs

    These constructs can contain single statement or ablock of statements using BEGIN..END

    m n .

    Basic SQLCopyright 2010 Pratian Technologieswww.pratian.com

    These constructs can be nested also.

  • 8/22/2019 Unit6 Programming With SQL Server.pdf

    6/51

    FLOW CONTROL CONSTRUCTS

    IF Statement Syntax

    IF search_condition

    statement_list

    ELSE IF search_condition

    statement_list

    Basic SQLCopyright 2010 Pratian Technologieswww.pratian.com

    ELSEstatement_list

    For Ex:

    IF @CourseId = 1

    SET @Fees = 1000;

  • 8/22/2019 Unit6 Programming With SQL Server.pdf

    7/51

    FLOW CONTROL CONSTRUCTS

    CASE Statement Syntax

    CASE case_value

    WHEN when_value THEN statement_list

    [WHEN when_value THEN statement_list] ... [ELSEstatement_list]

    Basic SQLCopyright 2010 Pratian Technologieswww.pratian.com

    Or

    CASE

    WHEN search_condition THEN statement_list

    [WHEN search_condition THEN statement_list] ... [ELSEstatement_list]

    END

  • 8/22/2019 Unit6 Programming With SQL Server.pdf

    8/51

    FLOW CONTROL CONSTRUCTS

    For Ex:

    DECLARE @shipping_cost INT;

    DECLARE @delivery_day INT;

    SET @delivery_day = DATEPART(day, getdate());

    Basic SQLCopyright 2010 Pratian Technologieswww.pratian.com

    e very_ ayWHEN 1 THENSET @shipping_cost = 20;

    WHEN 2 THENSET @shipping_cost = 15;

    WHEN 3 THENSET @shipping_cost = 10;

    ELSESET @shipping_cost = 5;

    END;

  • 8/22/2019 Unit6 Programming With SQL Server.pdf

    9/51

    FLOW CONTROL CONSTRUCTS

    GOTO Statement

    Implements a simple code jump construct

    Is used to jump to a particular line of the code

    Basic SQLCopyright 2010 Pratian Technologieswww.pratian.com

    Need to define a label before we use GOTO

  • 8/22/2019 Unit6 Programming With SQL Server.pdf

    10/51

    FLOW CONTROL CONSTRUCTS

    GOTO Syntax[label:] statement_list

    GOTO [label]

    For Ex:

    DECLARE @day INT;SET @day = 0;

    Basic SQLCopyright 2010 Pratian Technologieswww.pratian.com

    WHILE (@day

  • 8/22/2019 Unit6 Programming With SQL Server.pdf

    11/51

    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

    Basic SQLCopyright 2010 Pratian Technologieswww.pratian.com

    SET @Count = 0

    WHILE @Count

  • 8/22/2019 Unit6 Programming With SQL Server.pdf

    12/51

    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 intSET @Count = 0

    Basic SQLCopyright 2010 Pratian Technologieswww.pratian.com

    WHILE @Count

  • 8/22/2019 Unit6 Programming With SQL Server.pdf

    13/51

    FLOW CONTROL CONSTRUCTS

    WHILE Statement

    The WHILE Statement repeats the statement_list

    until the search_condition evaluates to true

    Syntax:

    Basic SQLCopyright 2010 Pratian Technologieswww.pratian.com

    searc _con t on

    BEGINstatement_list

    END

  • 8/22/2019 Unit6 Programming With SQL Server.pdf

    14/51

    FLOW CONTROL CONSTRUCTS

    For Ex:

    DECLARE @Count int

    SET @Count = 0

    WHILE @Count < 100

    BEGIN

    PRINT 'Hello World'

    Basic SQLCopyright 2010 Pratian Technologieswww.pratian.com

    SET @Count = @Count + 1END

  • 8/22/2019 Unit6 Programming With SQL Server.pdf

    15/51

    FLOW CONTROL CONSTRUCTS

    BREAK...CONTINUE

    BREAK and CONTINUE are used to exit, or

    continue executing WHILE or IF statements

    For Ex:

    Basic SQLCopyright 2010 Pratian Technologieswww.pratian.com

    oun n

    SET @Count = 0

    WHILE @Count < 100

    BEGIN

    PRINT 'Hello World'

    IF @Count = 10

    BREAK;

    ELSE

    SET @Count = @Count + 1

    END

  • 8/22/2019 Unit6 Programming With SQL Server.pdf

    16/51

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

    .

    Question Time

    Basic SQLCopyright 2010 Pratian Technologieswww.pratian.com

  • 8/22/2019 Unit6 Programming With SQL Server.pdf

    17/51

    ERROR HANDLING

    TRY/CATCH helps to write logic separate the actionand error handling code

    @@ERROR variable lets us know if any error hasbeen generated by the sql statements that havebeen executed

    Basic SQLCopyright 2010 Pratian Technologieswww.pratian.com

    The code meant for the action is enclosed in theTRY block and the code for error handling isenclosed in the CATCH block

    In case the code within the TRY block fails, thecontrol automatically jumps to the CATCH block

  • 8/22/2019 Unit6 Programming With SQL Server.pdf

    18/51

    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

    Basic SQLCopyright 2010 Pratian Technologieswww.pratian.com

    .

    ERROR_PROCEDURE: returns the name of the storedprocedure or trigger for which the error occurred.

    ERROR_MESSAGE: returns the full message text of theerror. The text includes the values supplied for any

    substitutable parameters, such as lengths, object names, ortimes

  • 8/22/2019 Unit6 Programming With SQL Server.pdf

    19/51

    ERROR HANDLING

    Syntax:BEGIN TRY

    sql_statement |statement_block

    END TRYBEGIN CATCH

    sql_statement |

    Basic SQLCopyright 2010 Pratian Technologieswww.pratian.com

    statement_blockEND CATCH

  • 8/22/2019 Unit6 Programming With SQL Server.pdf

    20/51

    ERROR HANDLING

    Example of TRYCATCH:BEGIN TRY

    DECLARE @X INT

    ---- Divide by zero to generate ErrorSET @X = 1/0

    PRINT 'Command after error in TRY block'END TRYBEGIN CATCH

    PRINT 'Error Detected'

    Basic SQLCopyright 2010 Pratian Technologieswww.pratian.com

    PRINT 'Command after TRY/CATCH blocks'

    Output

    Error DetectedCommand after TRY/CATCH blocks

  • 8/22/2019 Unit6 Programming With SQL Server.pdf

    21/51

    ERROR HANDLING

    Another Example of TRYCATCH:

    BEGIN TRY-- Generate a divide-by-zero error.

    SELECT 1/0;END TRY

    BEGIN CATCHSELECT

    Basic SQLCopyright 2010 Pratian Technologieswww.pratian.com

    _ ,

    ERROR_SEVERITY() AS ErrorSeverity,ERROR_STATE() AS ErrorState,

    ERROR_PROCEDURE() AS ErrorProcedure,ERROR_LINE() AS ErrorLine,ERROR_MESSAGE() AS ErrorMessage;

    END CATCH;GO

  • 8/22/2019 Unit6 Programming With SQL Server.pdf

    22/51

    ERROR HANDLING

    Example of TRYCATCH: RAISERROR functionBEGIN TRY

    DECLARE @MyInt INT;-- Following statement will create Devide by Zero Error

    SET @MyInt = 1/0;END TRYBEGIN CATCH

    DECLARE @ErrorMessage NVARCHAR(4000);SELECT @ErrorMessage = ERROR_MESSAGE();

    Basic SQLCopyright 2010 Pratian Technologieswww.pratian.com

    RAISERROR (@ErrorMessage, 16, 1);END CATCH;GO

    Result:Msg 50000, Level 16, State 1, Line 9

    Divide by zero error encountered.

  • 8/22/2019 Unit6 Programming With SQL Server.pdf

    23/51

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

    .

    Question Time

    Basic SQLCopyright 2010 Pratian Technologieswww.pratian.com

  • 8/22/2019 Unit6 Programming With SQL Server.pdf

    24/51

    PROCEDURES

    Custom programming scripts with embedded SQLstatements that are stored in a compiled form andexecuted directly by the MS SQL server

    Allow us to store logic [rules] on the database

    Basic SQLCopyright 2010 Pratian Technologieswww.pratian.com

    vto be sent between the server and the client

    Procedure names can be up to 64 characters long

  • 8/22/2019 Unit6 Programming With SQL Server.pdf

    25/51

    PROCEDURES

    Advantages of procedures

    Faster Execution:Reduced need for data transfer back andforth 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 throughout the a lication can be written once and can be reused.

    Basic SQLCopyright 2010 Pratian Technologieswww.pratian.com

    Selects, Inserts, etc.. Maintenance: If there are changes in the underlying

    database schema, code changes can be localized to a fewSPs

    Security: Direct access to tables by user programs is aproblem and with SPs, data access can be monitored, andlogged if necessary. Centralized security rules can beapplied

  • 8/22/2019 Unit6 Programming With SQL Server.pdf

    26/51

    PROCEDURES

    Syntax:

    CREATE PROCEDURE proc_name [proc_parameterdata_type[......]]

    AS

    BEGIN

    routine_body here;

    Basic SQLCopyright 2010 Pratian Technologieswww.pratian.com

    END

    proc_name : procedure nameproc_parameter : [default | OUTPUT ] param_name type

    data_type : any valid data type of Sql serverroutine_body : Valid SQL procedure statement

  • 8/22/2019 Unit6 Programming With SQL Server.pdf

    27/51

    PROCEDURES

    If you don't specify IN, OUTPUT for the parameter, it will defaultto IN

    An IN parameter is passed into the stored procedure to use

    internally

    An OUTPUT parameter is set within the procedure, butaccessed b the caller

    Basic SQLCopyright 2010 Pratian Technologieswww.pratian.com

    The name and data type of the parameter are used in the storedprocedure for referencing and setting values going in and out ofthe procedure

    The data type can be any valid data type for MS SQL

  • 8/22/2019 Unit6 Programming With SQL Server.pdf

    28/51

    PROCEDURES

    For Ex: Without parameters

    CREATE PROCEDURE GetStudents

    AS

    BEGIN

    SELECT * FROM Students

    END

    Basic SQLCopyright 2010 Pratian Technologieswww.pratian.com

    With IN Parameter CREATE PROCEDURE GetFeesForStudent @StudentId INT

    AS

    BEGIN

    SELECT Fees

    FROM Students

    WHERE StudentId = @StudentId

    END

  • 8/22/2019 Unit6 Programming With SQL Server.pdf

    29/51

    PROCEDURES

    With IN and OUT parameters CREATE PROCEDURE GetFeesForStudent @StudentId

    INT, @TotalFees INT OUTPUT

    AS

    BEGIN

    SELECT @TotalFees = Fees

    FROM Students

    Basic SQLCopyright 2010 Pratian Technologieswww.pratian.com

    tu ent = tu ent

    END

    Method to invoke a procedure

    EXEC GetStudents; EXEC GetFeesForStudent 1001;

    EXEC GetFeesForStudent 1001, @TotalFees;

  • 8/22/2019 Unit6 Programming With SQL Server.pdf

    30/51

    PROCEDURES

    ALTER PROCEDURE A procedure can be altered once created

    Syntax:

    ALTER PROCEDURE proc_name [proc_parameterdata_type[......]]

    AS

    BEGIN

    Basic SQLCopyright 2010 Pratian Technologieswww.pratian.com

    routine_body here;END

    proc_name : procedure nameproc_parameter : [ default | OUT ] param_name type

    data_type : any valid data type of Sql serverroutine_body : Valid SQL procedure statement

    DROP PROCDURE

    DROP PROCEDURE procedure_name

  • 8/22/2019 Unit6 Programming With SQL Server.pdf

    31/51

    USER DEFINED FUNCTIONS - UDFs

    User Defined Functions are compact pieces ofTransact SQL code, which can accept parameters,and return either a value, or a table

    Acts like a function in programming language. Can beparameterized and called any number of times

    Basic SQLCopyright 2010 Pratian Technologieswww.pratian.com

    Simpler to invoke than Stored Procedures from insideanother SQL statement

    Three types of UDFs Scalar UDFs

    Inline Table valued UDFs

    Multi-statement table valued UDFs

  • 8/22/2019 Unit6 Programming With SQL Server.pdf

    32/51

    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_namearameter_name data_t e =default , n

    Basic SQLCopyright 2010 Pratian Technologieswww.pratian.com

    _ _

    RETURNS scalar_data_type [WITH function_option]AS BEGIN

    Function_body

    RETURN scalar_expression

    END

  • 8/22/2019 Unit6 Programming With SQL Server.pdf

    33/51

    USER DEFINED FUNCTIONS - UDFs

    Scalar UDFs Example

    Basic SQLCopyright 2010 Pratian Technologieswww.pratian.com

  • 8/22/2019 Unit6 Programming With SQL Server.pdf

    34/51

    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

    Basic SQLCopyright 2010 Pratian Technologieswww.pratian.com

    Syntax: CREATE FUNCTION owner.function_name

    (parameter_name data_type [=default] [, n])

    RETURNS TABLE [WITH function_option]

    AS

    RETURN (

    SELECT_statement )

  • 8/22/2019 Unit6 Programming With SQL Server.pdf

    35/51

    USER DEFINED FUNCTIONS - UDFs

    Inline table valued UDFs Example:

    Basic SQLCopyright 2010 Pratian Technologieswww.pratian.com

  • 8/22/2019 Unit6 Programming With SQL Server.pdf

    36/51

    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 commandor a group of them gives us the capability to create aparameterized, non-updateable view of the data in theunderl in tables

    Basic SQLCopyright 2010 Pratian Technologieswww.pratian.com

    Within the create function command you must define thetable structure that is being returned

    After creating this type of user-defined function, you can useit in the FROM clause of a T-SQL command

  • 8/22/2019 Unit6 Programming With SQL Server.pdf

    37/51

    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

    Basic SQLCopyright 2010 Pratian Technologieswww.pratian.com

    Function_body

    RETURN

    END

  • 8/22/2019 Unit6 Programming With SQL Server.pdf

    38/51

    USER DEFINED FUNCTIONS - UDFs

    Example

    Basic SQLCopyright 2010 Pratian Technologieswww.pratian.com

  • 8/22/2019 Unit6 Programming With SQL Server.pdf

    39/51

    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.

    Basic SQLCopyright 2010 Pratian Technologieswww.pratian.com

    UDF does not support SET options. UDF does not Support Error Handling

    TRY/CATCH,RAISEERROR or @@ERROR are notallowed 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 multi-statement) cannot be used to return multiple result sets.

    USER DEFINED FUNCTIONS UDF

  • 8/22/2019 Unit6 Programming With SQL Server.pdf

    40/51

    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 keywordinstead of CREATE.

    Basic SQLCopyright 2010 Pratian Technologieswww.pratian.com

    DROP FUNCTION DROP FUNCTION function_owner.function_name;

    Example:

    DROP FUNCTION dbo.GetCustomersByCountry

    TRIGGERS

  • 8/22/2019 Unit6 Programming With SQL Server.pdf

    41/51

    TRIGGERS

    A trigger is a database object that is attached to atable.

    Is attached to a table and is onlyfired

    when anINSERT, UPDATE or DELETE occurs

    Basic SQLCopyright 2010 Pratian Technologieswww.pratian.com

    u u u .

    Triggers are used to enforce data integrity andbusiness rules

    TRIGGERS

  • 8/22/2019 Unit6 Programming With SQL Server.pdf

    42/51

    TRIGGERS

    Syntax:

    CREATE TRIGGER [owner.]trigger_name

    ON[owner.] table_nameFOR[INSERT/UPDATE/DELETE] ASIF UPDATE (column_name) [{AND/OR}

    PDATE L MN NAME ...

    Basic SQLCopyright 2010 Pratian Technologieswww.pratian.com

    _

    { sql_statements }

    TRIGGERS

  • 8/22/2019 Unit6 Programming With SQL Server.pdf

    43/51

    TRIGGERS

    For Ex: [To insert default CourseId after student insert]. CREATE TRIGGER dbo.ins_trig ON Students

    AFTER INSERT

    AS

    INSERT INTO StudentCourses (StudentId, CourseId)VALUES (inserted.StudentId, 1)

    Basic SQLCopyright 2010 Pratian Technologieswww.pratian.com

    INSERT INTO Students (StudentId, Name, Fees, JoinDate)

    VALUES (1004, Krishna Kumar S, 1000, 2010-12-05)

    TRIGGERS

  • 8/22/2019 Unit6 Programming With SQL Server.pdf

    44/51

    TRIGGERS

    INSERT Trigger

    When an INSERT trigger statement is executed, new rowsare 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

    Basic SQLCopyright 2010 Pratian Technologieswww.pratian.com

    .

    The inserted table can be examined by the trigger todetermine 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.

    TRIGGERS

  • 8/22/2019 Unit6 Programming With SQL Server.pdf

    45/51

    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

    Basic SQLCopyright 2010 Pratian Technologieswww.pratian.com

    Updated row is inserted into inserted table and the table isbeing updated

    TRIGGERS

  • 8/22/2019 Unit6 Programming With SQL Server.pdf

    46/51

    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;

    Basic SQLCopyright 2010 Pratian Technologieswww.pratian.com

    CURSORS

  • 8/22/2019 Unit6 Programming With SQL Server.pdf

    47/51

    CURSORS

    Cursors are used when the SQL Select statement isexpected to return more than one row

    Is a database object used by applications tomanipulate data in a set on a row-by-row basis

    Basic SQLCopyright 2010 Pratian Technologieswww.pratian.com

    u u u

    functions

    Way to use cursor

    Before using a cursor, it must be declared and its definitioncontains 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

    CURSORS

  • 8/22/2019 Unit6 Programming With SQL Server.pdf

    48/51

    CURSORS

    Syntax:

    DECLARE CURSOR FOR

    OPEN

    Basic SQLCopyright 2010 Pratian Technologieswww.pratian.com

    FETCH FROM INTO,

    CLOSE

    DEALLOCATE

    CURSORS

  • 8/22/2019 Unit6 Programming With SQL Server.pdf

    49/51

    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 */

    Basic SQLCopyright 2010 Pratian Technologieswww.pratian.com

    INSERT INTO StudentCourses (StudentId, CourseId)VALUES (@StudentId, 1);

    FETCH NEXT FROM StudentCursor INTO @StudentId

    /* READ NEXT RECORD */

    END

    CLOSE StudentCursor

    DEALLOCATE StudentCursor

    CURSORS

  • 8/22/2019 Unit6 Programming With SQL Server.pdf

    50/51

    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

    Basic SQLCopyright 2010 Pratian Technologieswww.pratian.com

    Keep the number of rows and columns in a cursor to aminimum

    Try to use READ ONLY cursors whenever possible

    Question Time

  • 8/22/2019 Unit6 Programming With SQL Server.pdf

    51/51

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

    .

    Question Time

    Basic SQLCopyright 2010 Pratian Technologieswww.pratian.com