SQL - create database and tables in one script

后端 未结 4 1739
太阳男子
太阳男子 2021-01-01 22:13

Sorry if already asked, but I can\'t find anything on this.

I am moving something over from MySQL to SQL Server I want to have a .sql file create a database and tabl

相关标签:
4条回答
  • 2021-01-01 22:42

    Put a GO command between queries.

    IF db_id('dbname') IS NULL 
        CREATE DATABASE dbname
    
    GO
    
    CREATE TABLE dbname.dbo.TABLE1 ( 
    ); 
    
    CREATE TABLE dbname.dbo.TABLEN ( 
    ); 
    

    As for putting the table statements in the IF, you wouldn't be able to because of the GO command. You could create additional IF statements afterwards, to check for each tables pre-existence.

    The syntax for a block if is:

    IF condition
    BEGIN
       ....
       ....
    END
    
    0 讨论(0)
  • 2021-01-01 22:58

    Between creating the database and creating the tables you will need a USE statement.

    USE dbname
    

    This way the tables will be created in the correct place, without having to specify the DB name on everything.

    Also, GO and BEGIN...END like everyone else is saying.

    0 讨论(0)
  • 2021-01-01 22:58

    You have to separate the statements with the GO keyword:

    sql query
    GO
    
    another sql query
    GO
    
    and so on
    
    0 讨论(0)
  • 2021-01-01 23:03

    By placing a GO between statements (to create separate batches of statements)

    0 讨论(0)
提交回复
热议问题