首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何检查SQL Server CE 3.5中是否存在表

如何检查SQL Server CE 3.5中是否存在表
EN

Stack Overflow用户
提问于 2011-06-11 22:03:24
回答 2查看 7.7K关注 0票数 2

我有一个数据库user.sdf在asp.net中,我想创建的表,我需要检查它首先检查它的存在是不是如果存在则不需要创建的表,否则创建新的表,我如何检查它,请帮助我解决这个问题。

EN

回答 2

Stack Overflow用户

发布于 2011-06-11 22:44:09

您可以查询SQL CE3.5中的架构视图,请看一下here

下面是一个您可以使用的简单扩展方法。

代码语言:javascript
复制
public static class SqlCeExtentions
{
  public static bool TableExists(this SqlCeConnection connection, string tableName)
  {
    if (tableName == null) throw new ArgumentNullException("tableName");
    if (string.IsNullOrWhiteSpace(tableName)) throw new ArgumentException("Invalid table name");
    if (connection == null) throw new ArgumentNullException("connection");
    if (connection.State != ConnectionState.Open)
    {
      throw new InvalidOperationException("TableExists requires an open and available Connection. The connection's current state is " + connection.State);
    }

    using (SqlCeCommand command = connection.CreateCommand())
    {
      command.CommandType = CommandType.Text;
      command.CommandText = "SELECT 1 FROM Information_Schema.Tables WHERE TABLE_NAME = @tableName";
      command.Parameters.AddWithValue("tableName", tableName);
      object result = command.ExecuteScalar();
      return result != null;
    }
  }
}

您可以使用上述方法,如下所示

代码语言:javascript
复制
using (SqlCeConnection connection = new SqlCeConnection(@"Data Source=MyDatabase1.sdf"))
{
  connection.Open();
  if (connection.TableExists("MyTable"))
  {
     // The table exists
  }
  else
  {
    // The table does not exist
  }
}
票数 9
EN

Stack Overflow用户

发布于 2013-02-24 08:47:58

作为替代方法,您可以查询该表并捕获抛出的异常。如果存在异常,则未找到该表,否则该表存在。

代码语言:javascript
复制
SELECT TOP 1 1 FROM TableName;

一个简单的性能测试比对INFORMATION_SCHEMA的查询有更好的结果。尽管我会认为对INFORMATION_SCHEMA的查询更简洁。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/6316336

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档