jose's profileSQL Server 2005 blogsBlogLists Tools Help

Blog


    July 26

    The SQL SERVER 2005 Try Catch Block

     
     
    SYNTAX
    BEGIN TRY
        <SQL Statements>
    END TRY
    BEGIN CATCH TRAN_ABORT
        <SQL Statements>
    END CATCH
    OVERVIEW
    Prior to sql server 2005 error handling is done by querying @@error after every line of execution. In sql server 2005, try catch block provides a new structure way of handling error similar to those of many development language such as VB, Java and C#

    One of  the advantage of try catch block over  its old friend @@error is that it enables transaction abort errors to be captured with no loss of the transaction context
    EXAMPLES

    a. constraint violation


    USE AdventureWorks

        BEGIN TRY
          UPDATE HumanResources.Employee
          SET Gender = 'X'
          WHERE EmployeeID = 1;
        END TRY
        BEGIN CATCH
          SELECT ERROR_NUMBER(  ) ErrorNumber,
          ERROR_STATE(  ) ErrorState,
          ERROR_SEVERITY(  ) ErrorSeverity,
          ERROR_MESSAGE(  ) ErrorMessage;
        END CATCH

     

    b. selecting from non existing table

    USE AdventureWorks;
    GO
    BEGIN TRY
        -- Table does not exist; object name resolution
        -- error not caught.
        SELECT * FROM NonexistentTable;
    END TRY
    BEGIN CATCH
        SELECT
            ERROR_NUMBER() as ErrorNumber,
            ERROR_MESSAGE() as ErrorMessage;
    END CATCH
     
    c. erroneous sp

    -- Verify that the stored procedure does not exist.
    IF OBJECT_ID ( N'usp_ExampleProc', N'P' ) IS NOT NULL
        DROP PROCEDURE usp_ExampleProc;
    GO
    -- Create a stored procedure that will cause an
    -- object resolution error.
    CREATE PROCEDURE usp_ExampleProc
    AS
        SELECT * FROM NonexistentTable;
    GO
    BEGIN TRY
        EXECUTE usp_ExampleProc
    END TRY
    BEGIN CATCH
        SELECT
            ERROR_NUMBER() as ErrorNumber,
            ERROR_MESSAGE() as ErrorMessage;
    END CATCH;
    D. division  by zero

    USE AdventureWorks;
    GO
    BEGIN TRY
        -- Generate a divide-by-zero error.
        SELECT 1/0;
    END TRY
    BEGIN CATCH
        SELECT
            ERROR_NUMBER() AS ErrorNumber,
            ERROR_SEVERITY() AS ErrorSeverity,
            ERROR_STATE() AS ErrorState,
            ERROR_PROCEDURE() AS ErrorProcedure,
            ERROR_LINE() AS ErrorLine,
            ERROR_MESSAGE() AS ErrorMessage;
    END CATCH;
    GO
     
    d. try catch with transaction
    USE AdventureWorks;
    GO
    BEGIN TRANSACTION;
    BEGIN TRY
        -- Generate a constraint violation error.
        DELETE FROM Production.Product
            WHERE ProductID = 980;
    END TRY
    BEGIN CATCH
        SELECT
            ERROR_NUMBER() AS ErrorNumber,
            ERROR_SEVERITY() AS ErrorSeverity,
            ERROR_STATE() as ErrorState,
            ERROR_PROCEDURE() as ErrorProcedure,
            ERROR_LINE() as ErrorLine,
            ERROR_MESSAGE() as ErrorMessage;
        IF @@TRANCOUNT > 0
            ROLLBACK TRANSACTION;
    END CATCH;
    IF @@TRANCOUNT > 0
        COMMIT TRANSACTION;
    GO
     
    e. try catch with xact- state
    USE AdventureWorks;
    GO
    -- Check to see if this stored procedure exists.
    IF OBJECT_ID (N'usp_GetErrorInfo', N'P') IS NOT NULL
        DROP PROCEDURE usp_GetErrorInfo;
    GO
    -- Create procedure to retrieve error information.
    CREATE PROCEDURE usp_GetErrorInfo
    AS
        SELECT
            ERROR_NUMBER() AS ErrorNumber,
            ERROR_SEVERITY() AS ErrorSeverity,
            ERROR_STATE() as ErrorState,
            ERROR_LINE () as ErrorLine,
            ERROR_PROCEDURE() as ErrorProcedure,
            ERROR_MESSAGE() as ErrorMessage;
    GO
    -- SET XACT_ABORT ON will render the transaction uncommittable
    -- when the constraint violation occurs.
    SET XACT_ABORT ON;
    BEGIN TRY
        BEGIN TRANSACTION;
            -- A foreign key constrain exists on this table. This
            -- statement will generate a constraint violation error.
            DELETE FROM Production.Product
                WHERE ProductID = 980;
        -- If the DELETE statement succeeds, commit the transaction.
        COMMIT TRANSACTION;
    END TRY
    BEGIN CATCH
        -- Execute error retrieval routine.
        EXECUTE usp_GetErrorInfo;
        -- Test XACT_STATE:
            -- If 1, the transaction is committable.
            -- If -1, the transaction is uncommittable and should
            --     be rolled back.
            -- XACT_STATE = 0 means that there is no transaction and
            --     a COMMIT or ROLLBACK would generate an error.
        -- Test if the transaction is uncommittable.
        IF (XACT_STATE()) = -1
        BEGIN
            PRINT
                N'The transaction is in an uncommittable state.' +
                'Rolling back transaction.'
            ROLLBACK TRANSACTION;
        END;
        -- Test if the transaction is committable
        IF (XACT_STATE()) = 1
        BEGIN
            PRINT
                N'The transaction is committable.' +
                'Committing transaction.'
            COMMIT TRANSACTION;  
        END;
    END CATCH;
    GO
     
    REMARKS
    1.  Try catch block can be nested
    2.  Only one block is allowed per batch
    3.  Catches all execution errors with severity greater than 10 that do not terminate the database connection
    4.  A TRY block must be followed immediately by an associated CATCH block. Placing any other statements 
          between the END TRY and BEGIN CATCH statements generates a syntax error.
    5.  GOTO statements cannot be used to enter a TRY or CATCH block. GOTO statements can be used to jump to a label within the same TRY or CATCH block or to leave a TRY or CATCH block.
    There is no finally block
     
    July 18

    Sampling SQL Data with TABLESAMPLE

    Sampling  Data with TABLESAMPLE

    Sampling, in demography and statistics, is the process of selecting units (e.g., people, organizations) from a population of interest so that by studying the sample we may fairly generalize our results back to the population from which they were chosen.
     
    SQL Server 2005  introduce  TABLESAMPLE  function to sample data from a table. With the advent of very large database, such those of the datawarehouse, sampling maybe of great use  to developers and data professional alike who may need only a random sample of the data.

    Syntax
     TABLESAMPLE [SYSTEM] (sample_number [ PERCENT | ROWS ] ) 
     [ REPEATABLE (repeat_seed) ]
     

    Sample TSQL codes:


    USE AdventureWorks ;
    GO
    SELECT *
    FROM Sales.Customer TABLESAMPLE SYSTEM (10 PERCENT) ;

     

    Syntax explanation
    TABLESAMPLE SYSTEM returns an approximate percentage of rows. It generates a random value for each physical 8 KB page in the table. Based on the random value for a page and the percentage specified in the query, a page is included in the sample or excluded. Each page that is included returns all rows in the sample result set. For example, when specifying TABLESAMPLE SYSTEM 10 PERCENT, SQL Server returns all the rows on approximately 10 percent of the specified table's data pages. If the rows are evenly distributed on the pages of the table, and if there is a sufficient number of pages in the table, the number of rows returned should approximate the sample size requested. However, as the random value generated for each page is independent of the values generated for any other page, it is possible that a larger, or smaller, percentage of pages than requested are returned. The TOP(n) operator can be used to limit the number of rows to a given maximum
     
    REPEATABLE indicates that a selected sample should be returned again. When specified with the same repeat_seed value, SQL Server returns the same subset of rows as long as no changes have been made to the table. When specified with a different repeat_seed value, SQL Server will likely return a different sample of the rows in the table. The following actions to the table are considered changes: insert, update, delete, index rebuild, index defragmentation, database restore, and database attach.
     
    NOTES ON TABLESAMPLE:
     
    1. TABLESAMPLE cannot be used with views.
    2. cannot be used with derived tables, tables from linked servers, and tables derived from table-valued functions, rowset functions, or OPENXML
    3. compatibility level of 9.0 is a must
    July 06

    Using SQL SERVER 2005 Synonyms

    Synonyms

     

    Synonyms are words with the same meaning. In SQL server 2005 synonyms works like a permanent alias.

     

    Microsoft SQL Server 2005 introduces the concept of a synonym. A synonym is an alternative name for a schema-scoped object. Client applications can use a single-part name to reference a base object by using a synonym instead of using a two-part, three-part, or four-part name to reference the base object.

    A synonym is a database object that serves the following purposes:

    • It provides an alternative name for another database object, referred to as the base object, that can exist on a local or remote server.
    • It provides a layer of abstraction that protects a client application from changes made to the name or location of the base object.

    Something to do:

     

    1.  Create a table with a very long name

    CREATE TABLE [dbo].[myverylonglonglonglongtablename](

                    [id] [int] IDENTITY(1,1) NOT NULL,

                    [field1] [nchar](10) COLLATE Latin1_General_CI_AS NULL,

     CONSTRAINT [PK_myverylonglonglonglongtablename] PRIMARY KEY CLUSTERED

    (

                    [id] ASC

    )WITH (PAD_INDEX  = OFF, IGNORE_DUP_KEY = OFF) ON [PRIMARY]

    ) ON [PRIMARY]

    2. insert some thing in the table

    declare @x int

    select @x=0

    while @x<>10

    begin

    select @x=@x+1

    INSERT INTO [AdventureWorks].[dbo].[myverylonglonglonglongtablename]

               ([field1])

         VALUES

               ('hellox')

    end

     

    3.  Use select statement on the table with the long name

     

                    Select * from [dbo].[myverylonglonglonglongtablename]

     

    4.  create and use the synonyms

     

    -- Create a synonym for the Product table in myverylonglonglonglongtablename

    CREATE SYNONYM shortname

    FOR [dbo].[myverylonglonglonglongtablename]

    GO

     

    -- Query the  table by using the synonym.

     

    select * from shortname