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;

        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))
                int databaseID = (int)cmd.ExecuteScalar();
                result = (databaseID > 0);
    catch (Exception)
        result = false;
    return result;

No comments:

Post a Comment

Linked In Profile

Follow me

Follow by Email

About Me

My photo
Expert Senior Software Developer