Sunday 3 June 2012

Check If a Table Exists



     In SQL Server, you may require to check if certain table exists in a database or not. This may be for Creating new table, or Access/Update/Drop an existing table, you want to check its existance first.

  Here are some common practices to get the result :

1. If you are seaching for Physical tables, then write :
 

      IF OBJECT_ID('TableName','U') IS NOT NULL
          BEGIN
            PRINT 'Table exists'
          END
        ELSE
          BEGIN
            PRINT 'Table does not exist'
          END


 
2. Another method for seaching for Physical tables :


      IF EXISTS (SELECT 1 FROM   INFORMATION_SCHEMA.TABLES
               WHERE  TABLE_SCHEMA = N'DataBaseName'
                    AND TABLE_NAME = N'TableName')
                 
          BEGIN
            PRINT 'Table exists'
          END
        ELSE
          BEGIN
            PRINT 'Table does not exist'
          END


3. If you are seaching for temp tables, then write :


      IF OBJECT_ID('TempDB..#Test') IS NOT NULL
          BEGIN
            PRINT 'Table exists'
          END
        ELSE
          BEGIN
            PRINT 'Table does not exist'
          END





 Reference: Govind Badkur(http://govindbadkur.blogspot.com)

No comments:

Post a Comment