How to execute multiple SQL scripts in a single file from C#?
我正在尝试从C#在单个文件中执行多个SQL脚本。 在脚本之间,我有
然后,我用
请提出如何从C#执行此类脚本的建议。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 | foreach (var sqlBatch in ScriptDetails.Split(new[] {"GO","Go","go","gO" }, StringSplitOptions.RemoveEmptyEntries)) { try { string[] prefixes = {"--","/*" }; bool resultchk = prefixes.Any(prefix => sqlBatch.StartsWith(prefix)); if (!resultchk) { connection.Open(); command.CommandText = sqlBatch; command.ExecuteNonQuery();//ExecuteReader(); ExecuteScalar() connection.Close(); Result.Add(new SQLResult { Final_message ="Success" }); } } catch (SqlException ex) { Result.Add(new SQLResult { Final_message = ex.Message.ToString(), Line_No = ex.LineNumber }); connection.Close(); } } |
我将尝试只打开一次连接以运行脚本的所有部分。
伪代码:
1 2 3 4 5 6 7 8 9 10 11 12 13 | use (var connection ...) { connection.Open(); foreach (var sqlBatch in ...) { use (var command = new Command(..., connection)) { command.CommandText = sqlBatch; ... command.ExecuteNonQuery(); } } } |