我知道我的问题似乎有点宽泛,但我会尽量做到具体而简短。所以我目前正在开发一个关于数据归档的c#程序。基本上,我会有一个按钮,当我点击它时,它应该在我的SQL服务器数据库中生成新表。
我的问题是执行查询的方法。我已经有一个sql脚本文件列表(用SSMS编写),我想在c#中执行它们(按顺序)。 我应该将脚本硬编码到我的c#程序中来创建表吗?它看起来像这样:
private void btnCreateTables_Click(object sender, EventArgs e){
string query = "IF OBJECT_ID('dbo.AuditCardTypeBenefit_TEST','U') IS NULL ";
query += "BEGIN ";
query += "CREATE TABLE[dbo].[AuditCardTypeBenefit_TEST]( ";
query += "[AuditID] [decimal](18, 0) IDENTITY(1,1) NOT NULL, ";
query += "[AuditType] [char](5) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL, ";
query += "[CardTypeBenefitID] [decimal](18, 0) NOT NULL, ";
query += "[EventCode] [varchar](8) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL, ";
query += "[CardTypeGroupID] [varchar](5) COLLATE SQL_Latin1_General_CP1_CI_AS NULL, ";
query += "[AgeFrom] [int] NULL, ";
query += "[AgeTo] [int] NULL, ";
query += "[Gender] [char](1) COLLATE SQL_Latin1_General_CP1_CI_AS NULL, ";
query += "[CreateBy] [nvarchar](128) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL, ";
query += "[CreateDate] [datetime] NOT NULL, ";
query += "[Status] [char](2) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL, ";
query += "[CancelReason] [varchar](250) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL, ";
query += "[LastChangeBy] [nvarchar](128) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL, ";
query += "[LastChangeDate] [datetime] NOT NULL, ";
query += "[RecordVersion] [timestamp] NOT NULL ";
query += ") ON [PRIMARY] ";
query += "END "; }
或者我应该通过在c#中读取文件(调用它们)来执行脚本文件?我想知道是否有可能按特定顺序阅读它们。此外,脚本文件中的某些SQL语句与c#中的一些SQL语句不兼容,例如GO语句。
我正在考虑使用上面刚刚发布的代码进行硬编码,因为它可以按照我想要的顺序执行表生成。问题是想象一下,如果我想创建说,50个表,那么代码行将会很长。
我的想法是点击按钮,然后它将在sql server中创建所有表。
什么建议最好?
编辑: 我尝试执行sql脚本文件,看看它是否可行。这是它:
private void btnCreateTables_Click(object sender, EventArgs e)
{
string constr = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
try
{
using (SqlConnection con = new SqlConnection(constr))
{
FileInfo file = new FileInfo("C:\\Users\\88106221\\Documents\\PromotionEvent_Test.sql");
string script = file.OpenText().ReadToEnd();
Server server = new Server(new ServerConnection(con));
server.ConnectionContext.ExecuteNonQuery(script);
}
}
catch(Exception ex)
{
MessageBox.Show(ex.Message);
textBox1.AppendText(string.Format("{0}", Environment.NewLine));
textBox1.AppendText(string.Format("{0} MainPage_Load() exception - {1}{2}", _strThisAppName, ex.Message, Environment.NewLine));
Debug.WriteLine(string.Format("{0} MainPage_Load() exception - {1}", _strThisAppName, ex.Message));
}
现在它说无法找到PromotionEvent_Test.sql的目录。我检查了目录,这是正确的。原因是什么?
答案 0 :(得分:1)
要运行脚本文件,请使用此C#方法。
public void CreateDataBase(string FileNameWithPath)
{
List<string> cmds = new List<string>();
if (File.Exists(_pFileNameWithPath))
{
TextReader tr = new StreamReader(FileNameWithPath);
string line = "";
string cmd = "";
while ((line = tr.ReadLine()) != null)
{
if (line.Trim().ToUpper() == "GO")
{
cmds.Add(cmd);
cmd = "";
}
else
{
cmd += line + "\r\n";
}
}
if (cmd.Length > 0)
{
cmds.Add(cmd);
cmd = "";
}
tr.Close();
}
if (cmds.Count > 0)
{
try
{
using (SqlCommand command = new SqlCommand())
{
command.Connection = new SqlConnection("ConnectionString To Master");
command.CommandType = CommandType.Text;
if (command.Connection.State == System.Data.ConnectionState.Closed)
{
command.Connection.Open();
}
for (int i = 0; i < cmds.Count; i++)
{
command.CommandText = cmds[i];
command.ExecuteNonQuery();
}
}
}
catch (Exception exp)
{
MessageBox(exp.Message);
}
}
}
并使用它
CreateDataBase ("C:\1.SQL");
CreateDataBase ("C:\2.SQL");
CreateDataBase ("C:\3.SQL");
CreateDataBase ("C:\4.SQL");
CreateDataBase ("C:\5.SQL");
CreateDataBase ("C:\6.SQL");
CreateDataBase ("C:\7.SQL");
CreateDataBase ("C:\8.SQL");
CreateDataBase ("C:\9.SQL");