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.
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 masteris run