From .net how to I send many “batches” of SQL to Sql-Server without lots of round trips?

此生再无相见时 提交于 2019-12-21 16:32:51

问题


We have code that reads in a set of SQL script file, and after doing some processing on them splits them into batches by finding the “GO” keyword and then sends each batch to Sql Server using a separate SqlCommon.

Is there a better way of doing this so we:

  • Don’t have as many round trips
  • Never have SQL Server waiting for the next batch
  • Run faster.

(The batches are mostly creating tables, index, views and stored procs. Speed is an issue as our integration tests calls the code often. The sql-server common line tools may not be installed on the machine that is running this code.)


回答1:


The fastest solution is in fact splitting on GO. However, another alternative is to use the SQL Management Objects (SMO) and send the entire script to SQL Server in one fell swoop as if you were using Management Studio.

var connectionString = ConfigurationManager.ConnectionStrings[ connectionStringName ].ConnectionString;
using ( var sqlConnection = new SqlConnection( connectionString ) )
{
    var server = new Server( new ServerConnection( sqlConnection ) );
    server.ConnectionContext.Connect();
    server.ConnectionContext.ExecuteNonQuery( sqlFileContents );
    server.ConnectionContext.Disconnect();
}

SQL Server Management Objects (SMO)




回答2:


2 ideas...

Package the script and modify it to be runnable as a dynamic SQL snippet. Upload the entire batch in a stream using nvarchar(max) and run it using sp_executesql on the server side. Since you control it for integration testing, dynamic SQL is not much of an issue.

Upload the entire batch to the server as a nvarchar(max). Save the file on the SQL Server machine using xp_cmdshell or CLR or other. Again using xp_cmdshell, use sqlcmd to run the script file.

With any sort of batching, you lose some way of identifying exactly where it broke, since you are automating integration testing after all.



来源:https://stackoverflow.com/questions/5593820/from-net-how-to-i-send-many-batches-of-sql-to-sql-server-without-lots-of-roun

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!