Dec 19, 2007

Check if a database or table exists using Sql Server 2005


The Object_ID() function in SQL Server can be utilised in a number of ways. One such utility is to verify if an object exists.

The Object_ID() takes in the object name and object type as parameters. The object name is the object used and the object type is the type of object used in a schema.

For example to check if a table exists in a database, use this query :

IF OBJECT_ID ('AdventureWorks.dbo.AWBuildVersion','U') IS NOT NULL
Print 'Table Exists'
ELSE
Print 'Table Does Not Exists'

where 'AdventureWorks.dbo.AWBuildVersion' is the object name and 'U' is the object type which represents a table

Similarly you can check for a stored procedure or a view by specifying the correct object type. You can get an entire list of object types over here.

To check if a database exists, you can use the DB_ID() function as shown below :

IF db_id('AdventureWorks') IS NOT NULL
Print 'Database Exists'
ELSE
Print 'Database Does Not Exists'

Submit this story to DotNetKicks

Related Posts In This Category



Widget by Hoctro | Jack Book

 
  Feedback:

comments

6 Responses to "Check if a database or table exists using Sql Server 2005"
  1. Anonymous said...
    June 11, 2008 11:06 AM

    thank you, this was very useful

  2. Anonymous said...
    July 5, 2008 8:12 PM

    Thanks, I was also looking for the same thing. Thank you.

  3. Anonymous said...
    September 25, 2008 11:06 AM

    Thanks for the information

  4. Anonymous said...
    January 23, 2009 5:22 AM

    Done this before, am having a blonde day so this was very helpful thanks!

  5. Anonymous said...
    January 23, 2009 5:24 AM

    Very useful, you can also do this if youre running across several db's in a cursor or something.

    declare @db_name varchar(255)
    set @db_name = 'db_test'
    /*only run in dbs that have view*/
    IF OBJECT_ID (@db_name+'.dbo.custom_count_dbm_mth2_vw','V') IS NOT NULL
    Print 'do this'
    ELSE
    Print 'do nothing or something else'

  6. Senthil said...
    February 18, 2009 1:39 AM

    Thank you very much

 

Copyright 2009 All Rights Reserved SQL Server Curry by Suprotim Agarwal