Link to home
Start Free TrialLog in
Avatar of flynny
flynnyFlag for United Kingdom of Great Britain and Northern Ireland

asked on

'CREATE SCHEMA' must be the first statment in a query batch

Hi all,

I am trying to create and read in a database dynamically using c#. I have exported to an SQL file from SQL Managment studio.

I have the following code;

try
        {
            string connectionString = WebConfigurationManager.ConnectionStrings["myConnectionString"].ConnectionString;

            using (SqlConnection connection = new SqlConnection(connectionString))
            {
                string createQuery = String.Format("CREATE DATABASE [{0}{1}]", dbPrefix, databaseName);

                using (SqlCommand command = new SqlCommand(createQuery, connection))
                {
                    try
                    {
                        connection.Open();
                        command.ExecuteNonQuery();
                    }
                    catch (System.Exception ex)
                    {
                        //log
                    }
                    finally
                    {
                        connection.Close();
                    }
                }

                //now read in and execute the script
                FileInfo file = new FileInfo(defaultDBScript);
                string script = file.OpenText().ReadToEnd();

                //sub in the databaseName
                script = script.Replace("@Database", dbPrefix + databaseName);
                script = script.Replace("GO", ";");
                    
                using (SqlCommand command = new SqlCommand(script, connection))
                {
                    try
                    {
                        connection.Open();
                        command.ExecuteNonQuery();
                    }
                    catch (System.Exception ex)
                    {
                       //log
                    }
                    finally
                    {
                        connection.Close();
                    }
                }
                
                file.OpenText().Close();
 
            }'

Open in new window


However I am getting the following error message?

Could someone please tell me how I can export a db so I can programatically read it into another using c#?
ASKER CERTIFIED SOLUTION
Avatar of Carl Tawn
Carl Tawn
Flag of United Kingdom of Great Britain and Northern Ireland image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Is it required to create Database and then execute the script ?

You can check Ref - https://support.microsoft.com/kb/307283/EN-US