0

I'm writing an application that creates a SQL Server database for another program. For this I load a large SQL-script containing the CREATE DATABASE, CREATE TABLE and so on.

The first lines of the script is:

/*CREATE DATABASE*/
USE [master]
GO
CREATE DATABASE [MultiRisk5] COLLATE Latin1_General_CI_AS
GO
USE [MultiRisk5]
GO

And the C# code:

var sqlConn = new SqlConnection("myConnection");
var cmd = new SqlCommand("mySqlScript", sqlConn);
sqlConn.Open();
cmd.ExecuteNonQuery();
sqlConn.Close();

When I run the program I get an exception on the USE statement that tells me that the database MultiRisk5 doesn't exist.

How can this be, when I just created the database? The script runs fine when executed in SQL Server Management Studio.

1
  • 5
    GO is not a SQL Server command. It is a batch separator for Management Studio. Commented Aug 2, 2011 at 14:10

3 Answers 3

1

You can't load a script in c# that has GO in it and run it.

GO is recognised the SQL Server client tools only, and as a batch separator. The database engine won't recognise it. See these questions for more on how to do this

Also, does the SqlConnection try to connect to MultiRisk5? if so, this will error too before USE master is run

Sign up to request clarification or add additional context in comments.

3 Comments

Wow. 2 downvotes now. One removed upvote. Some interesting voting patterns here
I'd added a +1, but -2 seems more like someone acting for motives other than valid scoring.
This is indubitably one of the errors they're encountering, so I've +1ed.
0

You may want to try executing your query in a try catch block to see what comes back. That would be a good first step into figuring out the issue.

Comments

0

Maybe your app does not have the appropriate rights to create the database ? You should check whether the database creation succeeds before going on.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.