Solved

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

Posted on 2014-04-28
2
509 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
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
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

Revamp Your Training Process

Drastically shorten your training time with WalkMe's advanced online training solution that Guides your trainees to action.

Question has a verified solution.

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

Problem Hi all,    While many today have fast Internet connection, there are many still who do not, or are connecting through devices with a slower connect, so light web pages and fast load times are still popular.    If your ASP.NET page …
This article aims to explain the working of CircularLogArchiver. This tool was designed to solve the buildup of log file in cases where systems do not support circular logging or where circular logging is not enabled
This is my first video review of Microsoft Bookings, I will be doing a part two with a bit more information, but wanted to get this out to you folks.
In this video you will find out how to export Office 365 mailboxes using the built in eDiscovery tool. Bear in mind that although this method might be useful in some cases, using PST files as Office 365 backup is troublesome in a long run (more on t…

627 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