简体   繁体   English

在SQL Server中使用OLE DB运行多个命令或SQL脚本

[英]Run multiple commans or sql script using OLE DB in SQL Server

It is possible to run multiple commands or sql script using OLE DB? 是否可以使用OLE DB运行多个命令或sql脚本? For example to run sql script to create database and its structure (tables, indexes, stored procedures...). 例如,运行sql脚本来创建数据库及其结构(表,索引,存储过程...)。

When I use CCommand class, I can run only one command. 使用CCommand类时,只能运行一个命令。 How can I run SQL script with multiple commands? 如何使用多个命令运行SQL脚本?

Thanks, Martin 谢谢马丁

The GO command which separates TSQL statements is NOT a SQL command, but a statement recognized by the front end only. 分隔TSQL语句的GO命令不是SQL命令,而是仅前端可识别的语句。

Therefore you need to explicitly split your script into several commands at "\\nGO" before passing the result to the command object. 因此,在将结果传递到命令对象之前,需要在“ \\ nGO”处将脚本显式拆分为多个命令。

Martin - I have had this same issue. 马丁-我也遇到过同样的问题。 I assume that when you load a script with one or more "go" in it you get an error? 我认为当您加载一个包含一个或多个“ go”的脚本时,会得到错误提示吗?

I have used SQL DMO in the past to run scripts with GO in them. 我过去曾使用SQL DMO在其中运行带有GO的脚本。 That does require that SQLDMO be installed on your target computer. 这确实需要在目标计算机上安装SQLDMO。

Another option is to use the .NET "String.Split("GO")" function, and loop the resulting array of strings, exexuting them one by one. 另一种选择是使用.NET“ String.Split(” GO“)”函数,并循环生成的字符串数组,逐个执行。

Like this: 像这样:

StreamReader file = File.OpenText("c:\\MyScript.sql");
SqlConnection conn = new SqlConnection("My connection string here...");
string fullCommand = file.ReadToEnd();
string[] splitOptions = new string[] {"go", "GO", "gO", "Go" };
foreach (string individualCommand in fullCommand.Split(splitOptions, StringSplitOptions.RemoveEmptyEntries))
{
    SqlCommand comm = new SqlCommand(individualCommand, conn);
    comm.ExecuteNonQuery();
}

Disclaimer: I have not tested the above code, but it should give you an idea of what is required :-) 免责声明:我尚未测试上面的代码,但是它应该使您了解所需的内容:-)

I've sent multiple statements like INSERT INTO;INSERT INTO (semicolons are not required in SQL Server. 我已经发送了多个语句,例如INSERT INTO; INSERT INTO(SQL Server中不需要分号。

Some statements (like CREATE FUNCTION) have to be the first statement in a "Batch". 某些语句(例如CREATE FUNCTION)必须是“批处理”中的第一条语句。 In SSMS and sqlcmd, you have a GO separator, which is a client-side tool for separating batches. 在SSMS和sqlcmd中,您具有GO分隔符,这是用于分隔批处理的客户端工具。 This is not an OLEDB feature, so you would have to send them separately - in a separate invocation in series or parallel (depending on whether your operations can run simultaneously). 这不是OLEDB功能,因此您必须分别发送它们-分别串行或并行调用(取决于操作是否可以同时运行)。

If you can get away from CCommand, I guess you could launch sqlcmd, since it supports GO batch separators. 如果您可以摆脱CCommand,我猜您可以启动sqlcmd,因为它支持GO批处理分隔符。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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