Can anyone explain why this works:
use MyDb1
if NOT EXISTS (select * from sys.objects where name = 'MyTable' and type = 'U' )
create table MyTable(MyColumn int not null)
use MyDb2
if NOT EXISTS (select * from sys.objects where name = 'MyTable' and type = 'U' )
create table MyTable(MyColumn int not null)
But this doesn’t:
use MyDb1
mylabel:
if NOT EXISTS (select * from sys.objects where name = 'MyTable' and type = 'U' )
create table MyTable(MyColumn int not null)
if(DB_NAME()='MyDb1')
begin
use MyDb2
goto mylabel
end
The flow is right and the 2nd check for IF NOT EXISTS works but when it tries to create the table I’m getting the following error
There is already an object named ‘MyTable’ in the database.
this is greatly simplified but getting this to work will save me a lot of duplicated table creations across two nearly identical databases
Very strange behaviour. If I were to guess, I would say it is the context of the “use database” sitting on top of the label:. I would never use the label in T-SQL, but your call.
The output from this test shows it going through the right motions, but just failing for no reason. If you uncomment the line marked <<< and comment the one above it, it then works correctly
output: