Solved

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

Posted on 2014-04-28
2
479 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
Comment Utility
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
Comment Utility
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

6 Surprising Benefits of Threat Intelligence

All sorts of threat intelligence is available on the web. Intelligence you can learn from, and use to anticipate and prepare for future attacks.

Join & Write a Comment

Suggested Solutions

For those of you who don't follow the news, or just happen to live under rocks, Microsoft Research released a beta SDK (http://www.microsoft.com/en-us/download/details.aspx?id=27876) for the Xbox 360 Kinect. If you don't know what a Kinect is (http:…
Introduction This article shows how to use the open source plupload control to upload multiple images. The images are resized on the client side before uploading and the upload is done in chunks. Background I had to provide a way for user…
Sending a Secure fax is easy with eFax Corporate (http://www.enterprise.efax.com). First, Just open a new email message.  In the To field, type your recipient's fax number @efaxsend.com. You can even send a secure international fax — just include t…
Polish reports in Access so they look terrific. Take yourself to another level. Equations, Back Color, Alternate Back Color. Write easy VBA Code. Tighten space to use less pages. Launch report from a menu, considering criteria only when it is filled…

743 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

Need Help in Real-Time?

Connect with top rated Experts

16 Experts available now in Live!

Get 1:1 Help Now