The method mentioned in the previous article "how to deploy a database with C #" has another problem. If the database script contains storeprocedure, the method I provided will not be executed, then I made the following modifications based on the original one, which can meet both the previous script execution and the execution of the script containing storeprocedure.
The general modification is to replace the original createdb function. The specific code is as follows:
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;
}
It was originally intended to make the execution simple and allow all database script commands to be executed at one time, ";" was used to replace the original "go ", this operation will make the database script containing storeprocedure fail to be executed successfully. The improved method is to split the original script command set and execute each command one by one. Although it seems that this method is slightly less efficient, it is actually not all at all, and the effect is the same as the original practice.
Another thing to note is that when a database fails to be created, it is easy to delete this incomplete database. You just need to execute the following script.
Use master
Go
If exists (select * From sysdatabases where name = 'mytest ')
Drop database mytest
Go
Finally, I would like to thank my friend for asking me questions!