This script fails to execute from PowerShell (sqlcmd) and directly from SQL Management Studio:
IF db_id('BANANATEST') is not null
BEGIN
print 'DB BANANATEST already exists. NO ACTION TAKEN.'
END
ELSE
BEGIN
print 'DB BANANATEST does NOT exist.'
print 'Restoring a backup of BANANATEST'
RESTORE DATABASE BANANATEST
FROM DISK = 'BANANATEST.original.bak' ;
print 'Creating User BANANATEST'
USE master
If Exists (select loginname from master.dbo.syslogins where name ='BANANATEST')
Begin
DROP LOGIN [BANANATEST]
END
CREATE LOGIN [BANANATEST] WITH PASSWORD=N'BANANATEST', DEFAULT_DATABASE=[master], DEFAULT_LANGUAGE=[us_english], CHECK_EXPIRATION=OFF, CHECK_POLICY=OFF
USE BANANATEST
ALTER USER [BANANATEST] WITH LOGIN = [BANANATEST]
END
The error is Syntax.
Msg 911, Level 16, State 1, Line 20 Database 'BANANATEST' does not exist. Make sure that the name is entered correctly.
While it is accurate, BANANATEST DB doesn't exist in the moment of query "compilation"... SQL Server doesn't realise that database WILL exist when it reaches this line.
How can I make it work? Either by ignoring syntax checks or whatever it make it work...
NOTE: The backup comes with a BANANATEST usr and I want to cover two scenarios:
- LOGIN already exists in SQL Server
- LOGIN does not exist
RESTOREandUSEinto separate batches using aGO