How to check SQL Server database is exists using C#.NET

How to check SQL Server database is exists using C#.NET

The following method using sys. schema and views such as sys.databases and sys.tables.
As we know that the old style sysobjects and sysdatabases and those catalog views have been deprecated since SQL Server.

private static bool CheckDatabaseExists(string connectionString, string databaseName)
{
    string sqlQuery;
    bool result = false;
    try
    {
        SqlConnection conn = new SqlConnection(connectionString);
        sqlQuery = string.Format("SELECT database_id FROM sys.databases WHERE Name = '{0}'", databaseName);
        using (conn)
        {
            using (SqlCommand cmd = new SqlCommand(sqlQuery, conn))
            {
                conn.Open();
                int databaseID = (int)cmd.ExecuteScalar();
                conn.Close();
                result = (databaseID > 0);
            }
        }
    }
    catch (Exception ex)
    {
        result = false;
    }
    return result;
}

Share this post

Leave a Reply

Your email address will not be published. Required fields are marked *