SQL SMO To Execute Batch TSQL Script

*爱你&永不变心* 提交于 2020-01-01 05:37:07

问题


I'm using SMO to execute a batch SQL script. In Management Studio, the script executes in about 2 seconds. With the following code, it takes about 15 seconds.

var connectionString = GetConnectionString();
// need to use master because the DB in the connection string no longer exists  
// because we dropped it already
var builder = new SqlConnectionStringBuilder(connectionString) 
{ 
    InitialCatalog = "master" 
};

using (var sqlConnection = new SqlConnection(builder.ToString()))
{
    var serverConnection = new ServerConnection(sqlConnection);
    var server = new Server(serverConnection);

    // hangs here for about 12 -15 seconds
    server.ConnectionContext.ExecuteNonQuery(sql);  
}

The script creates a new database and inserts a few thousand rows across a few tables. The resulting DB size is about 5MB.

Anyone have any experience with this or have a suggestion on why this might be running so slowly with SMO?


回答1:


SMO does lots of weird .. stuff in the background, which is a price you pay for ability to treat server/database objects in an object-oriented way.
Since you're not using the OO capabilites of SMO, why don't you just ignore SMO completely and simply run the script through normal ADO?




回答2:


The best and fastest way to upload records into a database is through SqlBulkCopy.
Particularly when your scripts are ~1000 records plus - this will make a significant speed improvement.
You will need to do a little work to get your data into a DataSet, but this can easily be done using the DataSet xml functions.



来源:https://stackoverflow.com/questions/4136834/sql-smo-to-execute-batch-tsql-script

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