How can i generate "CREATE DATABASE" script from existing sql server for all databases.

AP 0 Reputation points
2023-09-25T20:23:44.7933333+00:00

How can i generate "CREATE DATABASE" script from existing sql server for all databases.

SQL Server Other
{count} votes

3 answers

Sort by: Most helpful
  1. Pankaj Dhillon 5 Reputation points
    2023-10-14T00:56:27.07+00:00

    you can use PowerShell for this

    [System.Reflection.Assembly]::LoadWithPartialName('Microsoft.SqlServer.SMO') | out-null 
    
    $smos = new-object ('Microsoft.SqlServer.Management.Smo.Server') "sqlinstance"  
    
    $dbs=$smos.Databases 
    
    foreach($db in $dbs)
    {
        $dbname="filepathhere\"+$db.name+".sql" 
        $db.Script() | Out-File $dbname
    }
    
    1 person found this answer helpful.
    0 comments No comments

  2. Erland Sommarskog 121.4K Reputation points MVP Volunteer Moderator
    2023-09-25T21:49:31.9166667+00:00

    I still think this may be better with SMO, since they already know of the tons of options there are.

    Check out https://dbatools.io/ to see what they have available.

    0 comments No comments

  3. LiHongMSFT-4306 31,566 Reputation points
    2023-09-26T09:07:52.3266667+00:00

    Hi @AP

    How about this c# code:

    String Connectionstring = CCMMUtility.CreateConnectionString(false, txt_DbDataSource.Text, "master", "sa", "happytimes", 1000);
    
            SqlConnection con = new SqlConnection();
            con.ConnectionString = Connectionstring;
            bool resultdbexistencx = CCMMUtility.CheckDatabaseExists(con, txt_DbName.Text);
            if (!resultdbexistencx)
            {
                // if not exists create it check the user name for sub-admin avialibe or not.
    
                if (txt_DbName.Text.Trim() == string.Empty) return;
    
                string strDbCreate;
                strDbCreate = "CREATE DATABASE " + txt_DbName.Text + " ON PRIMARY " +
                "(NAME = " + txt_DbName.Text + "_Data, " +
                "FILENAME = 'D:\\" + txt_DbName.Text + "Data.mdf', " +
                "SIZE = 4MB, MAXSIZE = 10GB, FILEGROWTH = 100%) " +
                "LOG ON (NAME = " + txt_DbName.Text + "_Log, " +
                "FILENAME = 'D:\\" + txt_DbName.Text + ".ldf', " +
                "SIZE = 4MB, " +
                "MAXSIZE = 10GB, " +
                "FILEGROWTH = 100%)";
                SqlConnection sqlconn = new SqlConnection(Connectionstring);
                SqlCommand cmd = new SqlCommand(strDbCreate, sqlconn);
                try
                {
                    sqlconn.Open();
                    sqlconn.ChangeDatabase("master");
                    cmd.ExecuteNonQuery();
                }
               catch (Exception ex)
                {
                    Int32 dbRollbackResult = RollBackTheWholetransaction(txt_DbName.Text.Trim(), Convert.ToInt32(HospitalResult));
                    if (dbRollbackResult == 1)
                    {
                        Response.Write(ex.Message);
                        lblMessage.DisplayMessage(StatusMessages.ErrorMessage, "There is some problem while generating the database or database name doesn't avialible.");
                    }
                 }
    

    Please refer to Ram Singh's answer for more details: Generate database creation scripts.

    Best regards,

    Cosmog Hong


    If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".

    Note: Please follow the steps in our Documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.