Saturday, January 1, 2011

How to check SQL Server Database is Exists using C#

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 2005.
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;
}

Source: https://www.nilebits.com/blog/2020/06/how-to-check-sql-server-database-is-exists-using-c-net/

No comments:

Post a Comment