Solved

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

Posted on 2014-04-28
2
489 Views
Last Modified: 2014-04-28
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#?
0
Comment
Question by:flynny
2 Comments
 
LVL 52

Accepted Solution

by:
Carl Tawn earned 500 total points
ID: 40027146
The problem isn't in the exporting, it's with the fact that some statement type must exist as the first statement in a batch (CREATE SCHEMA, CREATE VIEW, etc).

So, what you need to do is split your file contents on the batch separator and execute each one individually:
//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);
                    
using (SqlCommand command = new SqlCommand("", connection))
{
    string[] statements = script.Split(new string[] { "GO" }, StringSplitOptions.RemoveEmptyEntries);

    try
    {
        connection.Open();
        foreach (string statement in statements)
        {
            command.CommandText = statement;
            command.ExecuteNonQuery();
         }
    }
    catch (System.Exception ex)
    {
        //log
    }
    finally
    {
        connection.Close();
    }
}

Open in new window

0
 
LVL 7

Expert Comment

by:Utkarsh Kulkarni
ID: 40027157
Is it required to create Database and then execute the script ?

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

Featured Post

Live: Real-Time Solutions, Start Here

Receive instant 1:1 support from technology experts, using our real-time conversation and whiteboard interface. Your first 5 minutes are always free.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

IntroductionWhile developing web applications, a single page might contain many regions and each region might contain many number of controls with the capability to perform  postback. Many times you might need to perform some action on an ASP.NET po…
It was really hard time for me to get the understanding of Delegates in C#. I went through many websites and articles but I found them very clumsy. After going through those sites, I noted down the points in a easy way so here I am sharing that unde…
Two types of users will appreciate AOMEI Backupper Pro: 1 - Those with PCIe drives (and haven't found cloning software that works on them). 2 - Those who want a fast clone of their boot drive (no re-boots needed) and it can clone your drive wh…
Established in 1997, Technology Architects has become one of the most reputable technology solutions companies in the country. TA have been providing businesses with cost effective state-of-the-art solutions and unparalleled service that is designed…

774 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question