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

问题描述

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

解决方法

        您可以在SQL CE 3.5中查询架构视图,请看这里。 这是您可以使用的简单扩展方法。
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
  }
}
    ,        或者,您可以查询表并捕获抛出的异常。 如果存在异常,则找不到该表,否则该表存在。
SELECT TOP 1 1 FROM TableName;
一个简单的性能测试比针对INFORMATION_SCHEMA的查询具有更好的结果。尽管我认为针对INFORMATION_SCHEMA的查询更为简洁。     

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...