简体   繁体   English

SQL批量查询插入

[英]SQL Bulk Query Inserts

So I have a list of id's stored in a JsonArray. 所以我有一个ID列表存储在JsonArray中。 Currently, I am looping through the id's like so: 目前,我正在遍历id如下:

'Insert ids into table
For Each userId As Int32 In idList
    command.CommandText = "INSERT INTO user_ids (id) VALUES (" & userId & ");"
    command.ExecuteNonQuery()
Next

When that runs, it executes about 100 queries give or take, depending on the size of the id list. 在运行时,它会根据id列表的大小执行大约100个给出或接受的查询。 What I am trying to do, is use a bulk query so that rather than doing 100 queries to the database, I can do them all in one query. 我想做的是使用批量查询,这样我可以对一个查询进行全部操作,而不是对数据库执行100个查询。 I have been looking at using DataSets and BulkCopy but I am not sure how I would implement it. 我一直在研究使用DataSets和BulkCopy,但不确定如何实现它。

Is there a better solution? 有更好的解决方案吗?

Any help would be appreciated. 任何帮助,将不胜感激。 Thanks. 谢谢。

Setting up to do a BULK INSERT or SqlBulkCopy would likely be more efficient, but with just about 100 rows it's questionable whether you'd see a noticeable improvement, or even any improvement at all... the time spent massaging the data to a BULK INSERT-friendly format could easily outweigh the database throughput gain here. 设置为执行BULK INSERTSqlBulkCopy可能会更高效,但是只有大约100行,是否会看到显着的改进,甚至根本没有任何改进,这是值得怀疑的……将数据海量化为BULK所花费的时间此处的INSERT友好格式很容易超过数据库吞吐量的增加。 You also need to weigh whether the increased code complexity and introduction of a new technique would justify any improvement that you did see. 您还需要权衡增加的代码复杂性和引入新技术是否可以证明您确实看到了任何改进。

Instead, I'd just go for keeping the the same query and connection objects in your loop, like this: 相反,我只是为了在循环中保留相同的查询和连接对象,如下所示:

Using cn As New SqlConnection("connection string here"), _
      cmd As New SqlCommand("INSERT INTO user_ids (id) VALUES ( @UserID )" )

    cmd.Parameters.Add("@UserID", SqlDbType.Integer)
    cn.Open()

    'Insert ids into table
    For Each userId As Int32 In idList
        cmd.Parameters("@UserID").Value = userId
        cmd.ExecuteNonQuery()
    Next
End Using

In addition to the nice side benefit of keeping your code safe from sql injection attacks, this code should be faster than what you have, because the database will be able to cache that execution plan during your loop, and thus skip the compile and generate plan steps as it executes individual query. 除了保持代码免受sql注入攻击的危害的好处之外,此代码还应该比您拥有的代码更快,因为数据库将能够在循环期间缓存该执行计划,从而跳过编译并生成计划在执行单个查询时逐步执行。

If this insert happens at regular intervals (such as once per day), you might also take a look at this KB article about using minimal logging: 如果此插入以固定间隔(例如每天一次)发生,则您还可以阅读有关使用最少日志记录的这篇知识库文章:

http://technet.microsoft.com/en-us/library/ms191244(v=sql.105).aspx http://technet.microsoft.com/en-us/library/ms191244(v=sql.105).aspx

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

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