您的位置:首页 > 数据库

Check if a database or table exists using Sql Server 2005

2008-04-02 13:42 761 查看



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'
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐