【问题标题】:SQL Server using XML to perform mass updates in single querySQL Server 使用 XML 在单个查询中执行批量更新
【发布时间】:2012-05-18 19:27:00
【问题描述】:

我一直在使用下面的示例代码 sn-p 来更新 SQL Server 2005 数据库表。它将List<T>(其中T 是具有一系列属性(字段)的自定义对象)转换为嵌套在行根元素内的行元素上的XML 属性。

通过这种方式,我在一个 SQL 事务中进行了大量的插入操作。按照这条类似的路线,我想提供一个 XML 系列的更新,而不是插入。我无法找到任何好的资源来说明如何调整这种方法。例如根据主键 A 说从 B 到 F 的更新。

conn.Open();
cmd = new SqlCommand();
cmd.Connection = conn;
cmd.CommandText = @"INSERT table (A,B,C,D,E,F) 
SELECT Tbl.Col.value('@A','nvarchar(50)'),
       Tbl.Col.value('@B','int'),
       Tbl.Col.value('@C','nvarchar(50)'),
       Tbl.Col.value('@D','nvarchar(1000)'),
       Tbl.Col.value('@E','nvarchar(50)'),
       Tbl.Col.value('@F','nvarchar(50)')
FROM @xml.nodes('//row') Tbl(Col)";
cmd.Parameters.Add("@xml", SqlDbType.Xml).Value = new XDocument(
new XDeclaration("1.0", "utf-8", "yes"),
new XElement("rows",
toInsert.Select(p => new XElement("row", new XAttribute("A", x.Prop1),
                     new XAttribute("B", x.Prop2),
                     new XAttribute("C", x.Prop3),
                     new XAttribute("D", x.Prop4),
                     new XAttribute("E", x.Prop5),
                     new XAttribute("F", x.Prop6))))).ToString();
Console.WriteLine(cmd.ExecuteNonQuery().ToString() + " row(s) affected.");
conn.Close();

【问题讨论】:

    标签: c# xml sql-server-2005


    【解决方案1】:

    如果您想坚持使用此方法,您可以修改插入并使用以下 sql 执行更新:

    update  yourTable 
            set b = Tbl.Col.value('@B','int')
            --other cols...
    from     yourTable y
    join    @xml.nodes('//row') Tbl(Col) on
            y.a = Tbl.Col.value('@A','nvarchar(50)')
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-09-11
      • 1970-01-01
      • 2015-11-26
      • 1970-01-01
      • 2016-11-02
      • 1970-01-01
      • 2013-01-15
      • 1970-01-01
      相关资源
      最近更新 更多