简体   繁体   中英

Ignore “missing” database while executing SQL

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 master is run

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM