我听播客博客已经有一段时间了,希望我不要打破这个。 问题是这样的:我必须向数据库中插入一个 xml。这将用于已经定义的表和字段。那么实现这一目标的最佳方法是什么?到目前为止,我倾向于程序化。我一直看到各种选项,一个是数据传输对象 (DTO),在 SQL Server 中有 sp_xml_preparedocument,用于将 XML 传输到对象并通过代码。
我正在使用 CSharp 和 SQL Server 2005。字段不是 XML 字段,它们是通常的 SQL 数据类型。
最佳答案
为了尝试提供帮助,我们可能需要一些说明。也许通过重述问题,您可以让我们知道这是否是您要问的:
如何在不依赖内置 xml 类型的情况下将现有 xml 导入 SQL 2005 数据库?
您已经提到的一个相当直接的解决方案是 sp_xml_preparedocument,结合 openxml。
希望下面的例子说明了正确的用法。有关更完整的示例,请查看 Using OPENXML 上的 MSDN 文档.
declare @XmlDocumentHandle int
declare @XmlDocument nvarchar(1000)
set @XmlDocument = N'<ROOT>
<Customer>
<FirstName>Will</FirstName>
<LastName>Smith</LastName>
</Customer>
</ROOT>'
-- Create temp table to insert data into
create table #Customer
(
FirstName varchar(20),
LastName varchar(20)
)
-- Create an internal representation of the XML document.
exec sp_xml_preparedocument @XmlDocumentHandle output, @XmlDocument
-- Insert using openxml allows us to read the structure
insert into #Customer
select
FirstName = XmlFirstName,
LastName = XmlLastName
from openxml ( @XmlDocumentHandle, '/ROOT/Customer',2 )
with
(
XmlFirstName varchar(20) 'FirstName',
XmlLastName varchar(20) 'LastName'
)
where ( XmlFirstName = 'Will' and XmlLastName = 'Smith' )
-- Cleanup xml document
exec sp_xml_removedocument @XmlDocumentHandle
-- Show the data
select *
from #Customer
-- Drop tmp table
drop table #Customer
如果您有一个 xml 文件并且正在使用 C#,那么定义一个执行类似上述操作的存储过程,然后将整个 xml 文件内容作为一个字符串传递给该存储过程应该会给您一种将 xml 导入现有表的相当直接的方法。
关于sql-server - 将 xml 传输到 SQL Server 的最佳方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59790/