Technical Article

udf_is_database_available

,

In many procedures, you'll have to check if a database is online or if it's not read-only, or if it's not in single-user mode. Instead of copy/past this code for in several scripts, I developed a function which does some basic checking for a database. These checks are:

  • make sure the database exists
  • make sure the status is 'online'
  • make sure it's NOT read-only (snapshots are also eliminated)
  • make sure access level is multi-user

The function returns true (1) if all these criteria match.

Use it in your code like

if dbo.udf_is_database_available(@databasename) = 0
begin
raiserror('Database %s is not prepared',16,1,@databasename)
return 1

end

if object_id('udf_is_database_available') is not null
    drop function udf_is_database_available
go

create function udf_is_database_available(@Databasename sysname)
/*
    Criteria:    - database must exist
                - multi-user access
                - not read-only
                - status ONLINE

    v20081105    "select count()" instead of "if exists"
*/returns bit as
begin
    return    (
                    select    count(*) 
                    from    master.sys.databases
                    where    name = @databasename
                    and        user_access = 0
                    and        is_read_only = 0
                    and        state = 0
                )
end
go

Rate

You rated this post out of 5. Change rating

Share

Share

Rate

You rated this post out of 5. Change rating