2009-07-29 52 views

回答

3
using(SqlConnection connection = 
    new SqlConnection(connectionString)) 
{ 
connection.Open(); 
DataTable dt = connection.GetSchema(); 
connection.Close(); 
} 

看到here

+0

以下是GetSchema上的MSDN文档 - http://msdn.microsoft.com/en-us/library/ms254934.aspx – RichardOD 2009-07-29 07:53:23

0

使用INFORMATION_SCHEMA

选择a.table_name 从INFORMATION_SCHEMA.TABLES一个在表格名LIKE'

5

此查询应该给你答案:

select count(id) from sysobjects where name = 'thetable' and type = 'U' 

如果计数是1表存在,如果它是0它不。

裹成一个方法:

private bool TableExists(string tableName) 
{ 
    using (SqlConnection conn = new SqlConnection(GetConnectionString())) 
    { 
     using (SqlCommand cmd = new SqlCommand("select count(id) from sysobjects where name = @tableName and type = 'U'", conn)) 
     { 
      cmd.Parameters.AddWithValue("@tableName", tableName); 
      conn.Open(); 
      int count = (int)cmd.ExecuteScalar(); 
      conn.Close(); 
      return count == 1; 
     } 
    } 
} 
1

对于支持它(至少2005年和2008年),你可以写INFORMATION_SCHEMA查询新的SQL Server版本。例如。如果存在用户表,则以下查询(对针对您的特定应用程序数据库运行而不是master)将返回一行。

SELECT * FROM information_schema.tables 
WHERE TABLE_NAME = 'Users' 
AND TABLE_TYPE = 'BASE TABLE' -- could be 'VIEW' 

或只是在你的数据库返回所有的表名是这样的:

SELECT TABLE_NAME FROM information_schema.tables 
WHERE TABLE_TYPE = 'BASE TABLE' -- could be 'VIEW' 

我相信你已经有了C#ADO代码运行查询(或者你可以在上述转变进入存储过程)。您可以收集大量其他有用信息,而无需担心所有参数/列/类型的神秘信息sysobjects

0

您需要的是查询SQLServer数据库中的sysobject表,以查找数据库中特定表/对象的存在。

SELECT 1 AS Exists FROM dbo.sysobject where name = @tableName AND xtype = 'U' 

打开SQLConnection并将此查询包装在SqlCommand对象中并执行它。

相关问题