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

时间:2011-06-11 14:03:24

标签: c# asp.net sql-server-ce

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

2 个答案:

答案 0 :(得分:9)

您可以在SQL CE 3.5中查询架构视图,看看here

这是一个可以使用的简单扩展方法。

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;
    }
  }
}

您可以按照以下方式使用以上

using (SqlCeConnection connection = new SqlCeConnection(@"Data Source=MyDatabase1.sdf"))
{
  connection.Open();
  if (connection.TableExists("MyTable"))
  {
     // The table exists
  }
  else
  {
    // The table does not exist
  }
}

答案 1 :(得分:0)

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

SELECT TOP 1 1 FROM TableName;

一个简单而简单的性能测试比针对INFORMATION_SCHEMA的查询具有更好的结果。虽然我认为对INFORMATION_SCHEMA的查询更清晰。