# Solved: SQLCMD database exists verify



## trusp (Dec 5, 2008)

Hi 
I am creating a dos based batch file for database backup & Restore.
Here I need to make the database to be "dbo use only" from the CLI 
So before restoring I need to execute the following command 
EXEC sp_dboption '%DB-NAME%','dbo use only','TRUE'
But here the issue is: If database already exists this line not makes any error.
Else if database was been dropped. Then it produces the following error: 
Msg 15010, Level 16, State 1, Server MT-SERVER123, Procedure sp_dboption, Line 64
The database 'testDatabase' does not exist. Use sp_helpdb to show available databases.
Available databases:
------
.....
....
So here I need to check whether a database exist and need to run the command:
EXEC sp_dboption '%DB-NAME%','dbo use only','TRUE'
This is the Script:
set UN=%1
set PWD=%2
set SER=%3
set DB=%4
sqlcmd -U %UN% -P %PWD% -S %SER% -Q "EXEC sp_dboption '%DB%','dbo use only','TRUE'"
sqlcmd -U %UN% -P %PWD% -S %SER% -Q "RESTORE DATABASE %DB% FROM DISK='%DB%.bak'"

Please help me out in this issue

Trusp


----------



## TheOutcaste (Aug 8, 2007)

Use this to branch to an error routine to ask for another file if the one specified doesn't exist:

*IF NOT EXIST %DB% goto DB_NOT_FOUND*

HTH

Jerry


----------



## trusp (Dec 5, 2008)

Thank you Jerry !!!


----------



## TheOutcaste (Aug 8, 2007)

Guess I should point out that if there is no 4th parameter specified, the If statement will fail.
So better to use this:
*If NOT EXIST [%DB%] Goto DB_NOT_FOUND
*
If the parameter is not specified, the statement becomes
*If NOT EXIST [] Goto DB_NOT_FOUND*, which should fail (unless you have a file named []

Always a good idea to check that all the parameters required have been specified, and that they are valid.

Jerry


----------

