Don't like ads? PRO users don't see any ads ;-)
Guest

Untitled

By: a guest on Jul 4th, 2012  |  syntax: None  |  size: 1.13 KB  |  hits: 14  |  expires: Never
download  |  raw  |  embed  |  report abuse  |  print
Text below is selected. Please press Ctrl+C to copy to your clipboard. (⌘+C on Mac)
  1. GOTO label after USE database switch
  2. use MyDb1
  3. if NOT EXISTS (select * from sys.objects where name = 'MyTable' and type = 'U' )
  4. create table MyTable(MyColumn int not null)
  5. use MyDb2
  6. if NOT EXISTS (select * from sys.objects where name = 'MyTable' and type = 'U' )
  7. create table MyTable(MyColumn int not null)
  8.        
  9. use MyDb1
  10.  
  11. mylabel:
  12. if NOT EXISTS (select * from sys.objects where name = 'MyTable' and type = 'U' )
  13. create table MyTable(MyColumn int not null)
  14.  
  15. if(DB_NAME()='MyDb1')
  16. begin
  17.     use MyDb2
  18.     goto mylabel
  19. end
  20.        
  21. set nocount on
  22. use tempdb
  23. create database db1
  24. create database db2
  25. GO
  26.  
  27. use db1
  28.  
  29. mylabel:
  30. print 'in-' + db_name()
  31. if NOT EXISTS (select * from sys.objects where name = 'MyTable' and type = 'U' )
  32. begin
  33.     print 'create-' + db_name()
  34.     create table MyTable(MyColumn int not null)
  35.     -- exec ('create table MyTable(MyColumn int not null)') -- <<<
  36. end
  37.  
  38. if(DB_NAME()='db1')
  39. begin
  40.     print 'switch'
  41.     use db2
  42.     goto mylabel
  43. end
  44.  
  45. GO
  46. use tempdb
  47. drop database db1
  48. drop database db2
  49.        
  50. in-db1
  51. create-db1
  52. switch
  53. in-db2
  54. create-db2
  55. Msg 2714, Level 16, State 6, Line 9
  56. There is already an object named 'MyTable' in the database.