Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Setting NOEXEC ON still executes "USE" statement

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?

like image 970
Ray Avatar asked Jul 02 '26 00:07

Ray


1 Answers

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
like image 157
zajonc Avatar answered Jul 05 '26 00:07

zajonc



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!