简体   繁体   中英

SQL SERVER 2005 USE statement

What is the best way to handle if USE {invalid_database_name} is failed? I would like to ignore the rest of the statements in such cases. This is so as to avoid accidentally run the script on wrong database. Thanks for your suggestion !!!

Run the script in SQLCMD mode in SSMS and use :on error exit . If you run the script form an app, use a library that is sqlcmd mode compatible, like dbutilsqlcmd .

Edit

What the many responses recommending various forms of IF and RETURN and sp_executesql are missing is that they only solve the problem of not executing a batch (the sequence delimited by GO ). This helps little when talking about a script . The batch that verifies the DB existence will skip the statements, fine, but the very next batch in the script will continue and do whatever it does (eg. create tables) in the current database, not in the desired database. Adding a check at the begging of each batch is tedious and error prone, placing the entire script in a single batch is often not possible. Best solution is to simple do an USE <inexisting name> and rely on the :on error exit to interrupt the script execution at first error.

you need to check if the Database with the name exists by

IF EXISTS (SELECT 1 FROM master.dbo.sysdatabases 
           WHERE ('[' + name + ']' = @dbname OR name = @dbname))
BEGIN
     --Your Code here
     [USE myDatabase]
END

To check if a Database exists:

IF DB_ID("<your database>" IS NOT NULL
BEGIN
    // Your code here
END

or if it is a stored procedure:

IF DB_ID("<your database>" IS NULL
BEGIN
    RETURN
END

That's better that searching in sysobjects.

Try Use This

begin try
declare @use nvarchar(50)
set @use= 'use MyDB'
exec sp_executesql @use

select top 1 * from MyDB.dbo.TableA


end try
begin catch
print @@ERROR   --Error Number of Database not Found
print Error_message() -- Proper Message
end catch

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM