Reputation: 1450
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.
Upvotes: 0
Views: 353
Reputation: 432311
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
Upvotes: 1
Reputation: 1524
Maybe your app does not have the appropriate rights to create the database ? You should check whether the database creation succeeds before going on.
Upvotes: 0
Reputation: 246
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.
Upvotes: 0