查询用户表是否存在的方法及举例

方法1:通过查询系统表:

1)测试查询:

1Declare
2@TableName VarChar(50)
3Set @TableName = 'tb’
4If Exists (Select * From   sysobjects
5Where name = @TableName And TYPE = 'u')
6Print 'EXISTS '
7Else
8Print 'NOT EXISTS '

2)查询应用举例:

数据库AdventureWorks,表:Sales.Store

1Use AdventureWorks
2If(Exists
3(Select * From dbo.sysobjects
4Where xtype = 'u' And Name = 'Store')) 
5/*此处为何不能是Sales.Store?是对引用表名的讲究还是Bug?*/
6
7Print 'Table Sales.Store in AdventureWorks Exists!'
8Else
9Print 'Table Sales.Store in AdventureWorks Not Exists!'

方法2:通过判断系统对象是否存在:

1)测试查询:

 1Declare @TableName VarChar(50)
 2Set @TableName = 'tb'
 3
 4If objectproperty(object_id(@TableName),'IsUserTable'Is Not Null 
 5Print 'Exists!'
 6Else
 7Print 'Not Exists '
 8
 9/*或者*/
10If (Exists
11(Select * From dbo.sysobjects
12Where id = object_id(N'@TableName'and objectproperty(id,'IsUserTable'= 1))
13/* N'@TableName'中的N表示NVarChar*/
14
15Print 'Exists!'
16Else
17Print 'Not Exists!'
18
19/*或者*/
20If object_id(@TableNameIs Not Null 
21Print 'Exists!'
22Else
23Print 'Not Exists!'
24
25/*或者*/
26If Exists (Select Object_id(@TableName))
27Print 'Exists!'
28Else
29Print 'Not Exists!'

2)查询应用举例:

数据库AdventureWorks,表:Sales.Store

 1Use AdventureWorks
 2If(Exists
 3(Select * From dbo.sysobjects
 4Where  id = object_id(N'Sales.Store'and objectproperty(id,'IsUserTable')=1))
 5/*此处表名必须是Sales.Store,若用Store则打印不存在*/
 6
 7Print 'Table Sales.Store in AdventureWorks Exists!'
 8Else
 9Print 'Table Sales.Store in AdventureWorks Not Exists!'
10
11/*或者*/
12If object_id('Sales.Store'Is Not Null
13/*此处表名用Sales.Store和Store都可以,有意思吧?*/
14
15Print 'Table Sales.Store in AdventureWorks Exists!'
16Else
17Print 'Table Sales.Store in AdventureWorks Not Exists!'
18
19/*或者*/
20If Exists (Select Object_id('Store'))
21/*此处表名用Sales.Store和Store都可以*/
22
23Print 'Table Sales.Store in AdventureWorks Exists!'
24Else
25Print 'Table Sales.Store in AdventureWorks Not Exists!'

P.S.:不同的方法要求不同,尤其是引用用户表名称的时候表现的比较突出。

posted on 2007-06-11 13:56  Zxhx  阅读(843)  评论(0)    收藏  举报

导航