如何检查在SQL Server CE 3.5是否存在一个表 [英] How can I check whether a table exists in SQL Server CE 3.5

查看:1792
本文介绍了如何检查在SQL Server CE 3.5是否存在一个表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在asp.net数据库 user.sdf ,我想创建该表是否存在,然后需要,我需要检查它检查它首先是不存在的不能创建表,否则创建新表我该怎么检查它的请帮我解决这个问题。

I have a database user.sdf in asp.net, I want to create the tables for that I need check it check it first exist are not if exist then need not create the tables, else create the new table how can I check it that please help me to resolve this.

推荐答案

您可以查询SQL CE 3.5的架构视图看看的here

You can query the schema views in SQL CE 3.5 take a look here.

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

Here is a simple extension method that you could use.

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

这篇关于如何检查在SQL Server CE 3.5是否存在一个表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆