2

我有一个有 200K+ 行的表,我需要每天更新。我的控制台应用程序每天都会生成所有这些数据,并且需要使用结果更新表格。

情况是我在一个缓慢的网络上运行,每次运行时更新/插入/删除的行不到 0.1%,所以显然还有空间需要优化。该表很简单 - 键列,加上 2 个 nvarchar 列。

所以我的问题是 - 在这种特殊情况下最好的方法是什么?我总是可以把它翻过来做一个 SQLBulkCopy,但是 SqlDataAdapter 会更有效吗?

谢谢,

麦克风

4

1 回答 1

1

将 XML 与存储过程的所有更改一起发送。

一趟数据库。

这是一个旧示例:

http://granadacoder.wordpress.com/2009/01/27/bulk-insert-example-using-an-idatareader-to-strong-dataset-to-sql-server-xml/

这是一个较小的示例,但显示了基础知识。

http://www.mindfiresolutions.com/Sending-Multiple-Records-As-XML-To-SQL-Server-Stored-Procedure-1861.php

将 xml 发送到存储过程。将 xml 分解为 @variable 或 #temp 表。使用@variable 或#temp 表执行更新/插入(或合并/UPSERT)。

编辑:

http://weblogs.asp.net/dwahlin/archive/2009/09/30/passing-multiple-records-to-a-stored-procedure-in-sql-server.aspx

另一个例子。

我喜欢做的是创建一个强大的数据集。将您的数据放入强大的数据集中。然后将 ds.GetXml() 发送到存储过程。

这样,您可以获得强类型(使用强数据集),并且您不必编写自己的 xml-maker,您可以使用 .GetXml()。提示:创建强数据集后,删除命名空间(tempuri 或类似的东西)

附录(2019 年春季)

由于 xml “膨胀”,我不再将项目放在强大的数据集(或任何数据集)中。

我编写了一个自定义 PocoObject-To-Xml 转换器(基于 xml 属性)并将其传递给存储过程。

下面是基于元素的......并显示了 xml-bloat

<Employees>
  <Employee>
      <EmployeeKey>123</EmployeeKey>
      <LastName>Smith</LastName>
      <FirstName>John</FirstName>
  </Employee>
  <Employee>
      <EmployeeKey>234</EmployeeKey>
      <LastName>Jones</LastName>
      <FirstName>Mary</FirstName>
  </Employee>
</Employees>

vs(更精简)

<Employees>
  <Employee EmployeeKey="123" LastName="Smith" FirstName="John" />
  <Employee EmployeeKey="234" LastName="Jones" FirstName="Mary" />
</Employees>

以及下面的自定义转换器代码:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;

namespace MyNamespace
{
    public class EmployeesToXmlConverter
    {
        public string ConvertToXmlString(ICollection<EmployeePoco> emps)
        {
            StringBuilder sb = new StringBuilder();
            XmlWriter writer = XmlWriter.Create(sb);

            writer.WriteStartElement("root");

            if (null != emps && emps.Any())
            {
                writer.WriteStartElement("Employees");
                foreach (EmployeePoco emp in emps)
                {
                    writer.WriteStartElement("Employee");
                    writer.WriteAttributeString("EmployeeKey", Convert.ToString(emp.EmployeeKey));
                    writer.WriteAttributeString("LastName", emp.LastName);
                    writer.WriteAttributeString("FirstName", emp.FirstName);
                    writer.WriteEndElement(); ////closing patient tag
                }

                writer.WriteEndElement(); ////closing emps tag

            }

            writer.WriteEndElement(); ////closing root tag
            writer.Close();
            string returnValue = sb.ToString();
            return returnValue;
        }
    }
}
于 2013-06-18T19:24:41.030 回答