1

我正在用 C# 编写一个 Winforms 应用程序,它将数据存储到 Xml,然后通过电子邮件发送。这两件事以其基本形式运行。

但现在我正在努力解决如何将这个 Xml 文件放入 SQL Server 数据库中。我知道您可以将值作为 Xml 存储到 SQL Server 中。但是有没有办法将 Xml 数据存储为intvarchar?或者一般来说,这是如何处理的?

提前致谢!

以下是 XML - 存储函数:

private void btnWriteCustomerToXml(object sender, EventArgs e) 
{
    Customer[] Kunden = new Customer[5];
    Customer[0] = new Customer(1, "John", "A", 10000);
    Customer[1] = new Customer(2, "John", "B", 20000);
    Customer[2] = new Customer(3, "John", "C", 30000);
    Customer[3] = new Customer(4, "John", "D", 40000);
    Customer[4] = new Customer(5, "John", "E", 50000);

    using (XmlWriter writer = XmlWriter.Create("TestMail.xml"))
    {
       writer.WriteStartDocument();
       writer.WriteStartElement("Employee");

       foreach (Customer employee in Customer)
       {
           writer.WriteStartElement("Employee");
           writer.WriteElementString("ID", employee.Id.ToString());
           writer.WriteElementString("Vorname", employee.FirstName);
           writer.WriteElementString("Nachname", employee.LastName);

           writer.WriteEndElement();
       }

       writer.WriteEndElement();
       writer.WriteEndDocument();

       string output = "XML file was successfully created!";
       MessageBox.Show(output);
   }
}           
4

1 回答 1

1

您可以使用 SQL Server 中的本机 XQuery 支持将您的 XML“分解”为关系数据并将其存储 - 如下所示:

-- declare input - could be the input parameter of a stored procedure or something
DECLARE @input XML = '<Employees><Employee><ID>4040</ID><Vorname>Dieter</Vorname><Nachname>Mueller</Nachname></Employee></Employees>'

-- INSERT INTO your table
INSERT INTO dbo.Employee(ID, Vorname, Nachname)
    -- shred the incoming XML into rows of data, based on the XPath /Employees/Employee
SELECT
    XEmp.value('(ID)[1]', 'int'),
    XEmp.value('(Vorname)[1]', 'varchar(50)'),
    XEmp.value('(Nachname)[1]', 'varchar(50)')
FROM 
    @input.nodes('/Employees/Employee') AS XTbl(XEmp)
于 2013-11-12T09:24:22.580 回答