检查表名是否存在SQL

时间:2014-06-19 17:52:23

标签: c# sql database sql-server-ce

如何在创建新表之前检查表是否已存在?

更新代码:

    private void checkTable()
            {

                string tableName = quotenameTxt.Text + "_" + firstTxt.Text + "_" + surenameTxt.Text;
                string connStr = @"Data Source=|DataDirectory|\LWADataBase.sdf";
             //   SqlCeConnection conn = new SqlCeConnection(connStr);
            //    if (conn.State == ConnectionState.Closed) { conn.Open(); }
                using (SqlCeConnection conn = new SqlCeConnection(connStr))
    {
        conn.Open();    
        SqlCeCommand cmd = new SqlCeCommand(@"SELECT * 
                                              FROM INFORMATION_SCHEMA.TABLES 
                                              WHERE TABLE_NAME = @tname", conn);
        cmd.Parameters.AddWithValue("@tname", tableName);
        SqlCeDataReader reader = cmd.ExecuteReader();
        if(reader.Read()){
            MessageBox.Show("Table exists");}
        else{
            MessageBox.Show("Table doesn't exist");
createtable();}

2 个答案:

答案 0 :(得分:1)

Sql Server Compact支持INFORMATION_SCHEMA视图

using (SqlCeConnection conn = new SqlCeConnection(connStr))
{
    conn.Open();    
    SqlCeCommand cmd = new SqlCeCommand(@"SELECT TOP 1 * 
                                          FROM INFORMATION_SCHEMA.TABLES 
                                          WHERE TABLE_NAME = @tname", conn);
    cmd.Parameters.AddWithValue("@tname", tableName)
    SqlCeDataReader reader = cmd.ExecuteReader();
    if(reader.Read())
        Console.WriteLine("Table exists");
    else
        Console.WriteLine("Table doesn't exist");

}

修改 在版本3.5中,似乎不接受TOP 1指令。但是,给定WHERE子句它应该没有区别使用它,或者不使用它,使其工作只需将查询更改为

SqlCeCommand cmd = new SqlCeCommand(@"SELECT * FROM INFORMATION_SCHEMA.TABLES 
                                      WHERE TABLE_NAME = @tname", conn);

第二次编辑 查看创建表的代码 (在聊天中,我建议将其添加到完整性的问题中)

using (SqlCeCommand command = new SqlCeCommand( 
        "CREATE TABLE ['" + tableName + "'] " + 
        "(Weight INT, Name NVARCHAR, Breed NVARCHAR)", con)) 

tableName变量周围的单引号成为表名称的一部分。但是对表的检查不存在使用引号。并且您的代码落在试图再次使用引号创建表的路径上。只需删除名称周围的引号即可。他们不需要。

答案 1 :(得分:0)

您可以使用SqlClientConnection获取数据库中所有对象的列表。

private void checkTable()
{
    string tableName = quotenameTxt.Text + "-" + firstTxt.Text + "-" + surenameTxt.Text;
    string connStr = @"Data Source=|DataDirectory|\LWADataBase.sdf";

    using (SqlCeConnection conn = new SqlCeConnection(connStr))
    {
        bool isTableExist = conn.GetSchema("Tables")
                                .AsEnumerable()
                                .Any(row => row[2] == tableName);
    }

    if (!isTableExist)
    {
        MessageBox.Show("No such data table exists!");
    }
    else
    {
        MessageBox.Show("Such data table exists!");
    }
}

来源:https://stackoverflow.com/a/3005157/1271037