简体   繁体   中英

Microsoft SQL Server CE Check if table exists

I am trying to check if a table exists in Microsoft SQL Server, but somehow the function I use always returns that it doesn't exist, and the output doesn't specify that an exception was thrown.

This occurs both before I created the table (which is expected), as well as after I created the table (which is not expected).

This is the function I am using:

/// <summary>
/// Checks  if a certain Sql Server Table exists
/// </summary>
/// <param name="_databasename">The name of the database</param>
/// <param name="_password">The password of the database</param>
/// <param name="_tablename">The name of the table to check</param>
/// <returns>
///     'true' if table exists
///     'false' if table not exists or if an exception was thrown
/// </returns>
public Boolean TableExists(String _databasename, String _password, String _tablename)
{
    if (!_databasename.Contains(".sdf")) { _databasename = _databasename + ".sdf"; }
    try
    {
        String connectionString = "DataSource=" + _databasename + "; Password=" + _password;
        SqlCeConnection conn = new SqlCeConnection(connectionString);

        if (conn.State==ConnectionState.Closed) { conn.Open(); }

        using (SqlCeCommand command = conn.CreateCommand())
        {
            command.CommandType = CommandType.Text;
            command.CommandText = "SELECT * FROM Information_Schema.Tables WHERE TABLE_NAME = '" + _tablename + "'";
            Int32 count = Convert.ToInt32(command.ExecuteScalar());

            if (count == 0)
            {
                Debug.WriteLine("Table " + _tablename + " does not exist.");
                return false;
            }
            else
            {
                Debug.WriteLine("Table " + _tablename + " exists.");
                return true;
            }
        }
    }
    catch(Exception _ex)
    {
        Debug.WriteLine("Failed to determine if table " + _tablename + " exists: " + _ex.Message);
        return false;
    }
}

There clearly is something I am missing here, but I just can't seem to find out what that is.

ExecuteScalar returns the first column of the first row retrieved by the query.
Supposing that your table really exist, the database name is correct and in the expected location, then the first column of the row returned is from TABLE_CATALOG, a nvarchar column.

Pheraphs you could try to change your query to:

command.CommandText = "SELECT COUNT(*) FROM Information_Schema.Tables " + 
                      "WHERE TABLE_NAME = .......";

Said that, I still can't explain why you don't get an exception when you try to convert to an int the return value of ExecuteScalar.....

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM