|
private bool CreateDB( ref SqlConnection sqlConn)
{
string strQuery;
string[] strComms;
bool blnBreaked = false;
if( ReadSQLFromFile( out strQuery))
{
strQuery = strQuery.Replace( "GO/r/n", ";" );
strComms = strQuery.Split(';' );
SqlCommand sqlComm = new SqlCommand();
sqlComm.Connection = sqlConn;
foreach( string strComm in strComms)
{
sqlComm.CommandText = strComm;
try
{
sqlComm.ExecuteNonQuery();
}
catch( SqlException sqlErr)
{
MessageBox.Show( sqlErr.Message );
blnBreaked = true;
break;
}
catch{
blnBreaked = true;
break;
}
}
sqlComm.Dispose();
if( !blnBreaked) return true;
}
return false;
}
Originally for simplicity of execution, all database script commands were executed at once, and ";" was used to replace the original "GO". Such an operation would make the database script containing StoreProcedure unable to execute successfully. The way to improve is to split the original script command set, and then execute each command one by one. Although it seems that this method is slightly less efficient, it is not always true, and the effect achieved is the same as the original method.
Another point to note is that when the database creation fails, it is necessary to delete this incomplete database. In fact, the method is very simple, just execute the following script.
use master
GO
if exists (select * from sysdatabases where name='mytest')
drop database mytest
GO |
|