【问题标题】:Dynamically insert multiple xml data into sql server tables using single procedure使用单个过程将多个 xml 数据动态插入到 sql server 表中
【发布时间】:2023-03-07 09:46:01
【问题描述】:

我需要帮助以使用单个过程将不同格式的 xml 数据插入 SQL Server 数据库>

例如:

<Items>
    <item></item>
    <item></item>
    <item></item>
</Items>

<Products>
    <product></product>
    <product></product>
    <product></product>
</Products>

所以我需要一个程序将数据插入数据库,以 xml 作为输入。 (我有近 20 种 xml 格式),我将只传递一个 xml 作为输入,但不是全部。

问候 贾亚钱德拉

【问题讨论】:

  • 不要尝试用一个程序来做到这一点!那将是一个巨大的、凌乱的、笨拙的怪物,并且随着时间的推移将无法维护!如果您有 20 种格式 - 您需要 20 种不同的查询才能将这些 XML 文档插入您的 SQL Server
  • 欢迎使用 StackOverflow:如果您发布代码、XML 或数据示例,在文本编辑器中突出显示这些行并单击“代码示例”按钮 ({ } ) 在编辑器工具栏上很好地格式化和语法突出显示它!
  • 那么问题是什么?
  • 你有大约 20 个用于这些 xml 的表?

标签: sql-server xml


【解决方案1】:

你可以试试:

create procedure spInsertData
(
    @data xml
)
as
begin
    set nocount on

    if @data.exist('/Items') = 1
    begin
        insert into Items (Name)
        select T.c.value('text()[1]', 'nvarchar(100)')
        from @data.nodes('/Items/Item') T(c)
        where not exists (select 1 from Items where Name = T.c.value('text()[1]', 'nvarchar(100)'))

        return;
    end
    else if @data.exist('/Products') = 1
    begin
        insert into Products (Name)
        select T.c.value('text()[1]', 'nvarchar(100)')
        from @data.nodes('/Products/Product') T(c)
        where not exists (select 1 from Products where Name = T.c.value('text()[1]', 'nvarchar(100)'))

        return;
    end
    -- etc.

end

【讨论】:

  • 我会将其中一个 xml 作为输入,但不会同时传递。
猜你喜欢
  • 1970-01-01
  • 2022-01-13
  • 1970-01-01
  • 2011-06-13
  • 1970-01-01
  • 2016-03-28
  • 2011-01-16
  • 1970-01-01
  • 2017-01-26
相关资源
最近更新 更多