I am writing a batch file that checks the existence of a database, and based on the outcome batch will execute other statements.
FOR /F "usebackq" %%S IN ( `sqlcmd.exe -S %server% -d master -U %username% -P !password! ^
-Q "set nocount on; select count(*) from dbo.sysdatabases where [name]='$(inputDatabase)'" -v inputDatabase="%databaseName%"` ) DO (
SET existsDB=%%S
)
if !existsDB! EQU 1 (
REM DO SOMETHING
) else (
REM DO SOMETHING
)
Dynamic assignment of database name fails. Returns the "Sqlcmd: 'TestDB': Invalid argument. Enter '-?' for help."
I would appreciate any directions to solve the issue.
Following code checks not only the database name, but also the login credentials and the server name.
SET _chk_DB=server
FOR /F "usebackq" %%S IN (`sqlcmd.exe -S %_svr% -d master -U %_usr%
-P %_psw% ^
-Q "set nocount on; select count(*) from dbo.sysdatabases where
[name]='%_dtb%'" `) DO (
SET _chk_DB=%%S
)
IF [%_chk_DB%]==[server] SET _returncode=1
IF [%_chk_DB%]==[login] SET _returncode=2
IF [%_chk_DB%]==[0] SET _returncode=4