Search code examples
c#sql-servermaster-db

Querying master.sys.databases view in SQL Server 2008 R2 from c# is not working


I'm using the code below to find if a database exists but the ExecuteNonQuery always returns -1.

I've seen the master.sys.databases view and it has the database POS

SqlConnection tmpConn = new SqlConnection("Data Source=localhost\\SQLEXPRESS;Initial Catalog=master;Integrated Security=True");

sqlCheckDBQuery = "SELECT * FROM master.sys.databases where name = \'aspnetdb\'";

using (tmpConn)
{
    try
    {
        tmpConn.Open();
        tmpConn.ChangeDatabase("master");
    }
    catch (Exception)
    {
        MessageBox.Show("SQLServer Express Database is either not installed or not running!", "Database Error!", MessageBoxButtons.OK, MessageBoxIcon.Error);
        Application.Exit();
    }

    using (SqlCommand sqlCmd = new SqlCommand(sqlCheckDBQuery, tmpConn))
    {
        int exists = sqlCmd.ExecuteNonQuery();

        if (exists <= 0)
            databaseExists = false;
        else
            databaseExists = true;
    }
}

Solution

  • in this particular instance you can use a scalar query instead of a data reader.

    sqlCheckDBQuery = "SELECT count(1) FROM master.sys.databases where name = 'aspnetdb'";
    var count = (int)sqlCmd.ExecuteScalar();
    databaseExists = count > 1;