When executing the following in SSMS;
if not exists (select * from sys.databases where name = 'SWFUAT')
begin
print 'The UAT database (SWFUAT) does not exist...'
set noexec on;
end
go
use SWFUAT;
go
The following is displayed;
The UAT database (SWFUAT) does not exist...
Msg 911, Level 16, State 1, Line 20
Database 'SWFUAT' does not exist. Make sure that the name is entered correctly.
Shouldn't the compiler just ignore the "use" statement?
If I understand your question correctly then you want to execute
use SWFUAT;
only when the SWFUAT database is exist.
Unfortunately because of this remark
USE is executed at both compile and execution time and takes effect immediately. Therefore, statements that appear in a batch after the USE statement are executed in the specified database.
described here you can't simply use the SET NOEXEC in your case.
To achieve what you need you should replace your code with for example this
if not exists (select * from sys.databases where name = 'SWFUAT')
begin
print 'The UAT database (SWFUAT) does not exist...'
end else begin
use SWFUAT;
end
go
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With