繁体   English   中英

SQL Server 2008在XML列中查找和替换元素

[英]SQL Server 2008 find and replace elements in XML column

在下表中:

CREATE TABLE [dbo].[GDB_ITEMS](
    [ObjectID] [int] NOT NULL,
    [UUID] [uniqueidentifier] NOT NULL,
    [Type] [uniqueidentifier] NOT NULL,
    [Name] [nvarchar](226) NULL,
    [PhysicalName] [nvarchar](226) NULL,
    [Path] [nvarchar](512) NULL,
    [Url] [nvarchar](255) NULL,
    [Properties] [int] NULL,
    [Defaults] [varbinary](max) NULL,
    [DatasetSubtype1] [int] NULL,
    [DatasetSubtype2] [int] NULL,
    [DatasetInfo1] [nvarchar](255) NULL,
    [DatasetInfo2] [nvarchar](255) NULL,
    [Definition] [xml] NULL,
    [Documentation] [xml] NULL,
    [ItemInfo] [xml] NULL,
    [Shape] [geometry] NULL,
 CONSTRAINT [R2_pk] PRIMARY KEY CLUSTERED 
(
    [ObjectID] ASC
)

ALTER TABLE [dbo].[GDB_ITEMS]  WITH CHECK ADD  CONSTRAINT [g1_ck] CHECK  (([Shape].[STSrid]=(4326)))
GO

[Documentation]列包含数百个xml项和元素。 我试图用T-SQL来替换一系列元素:

  <NPS_Info>
    <MetaPurp>NPS</MetaPurp>
    <NPS_Unit>
      <UnitCode>MANDATORY for Data Store: NPS Alpha Unit Code (ACAD)</UnitCode>
      <UnitType>MANDATORY for Data Store: NPS Unit Type (National Park, National Monument, etc)</UnitType>
    </NPS_Unit>
  </NPS_Info>

有了这个:

<NPS_Info>
  <MetaPurp>NPS</MetaPurp>
  <MetaPurp>CSDGM</MetaPurp>
  <MetaPurp>OnlineData</MetaPurp>
  <NPS_Unit>
    <UnitCode>ABCD</UnitCode>
    <UnitType>Park</UnitType>
  </NPS_Unit>
  <DatStore>
    <Category>Landscape</Category>
    <Category>Monitoring</Category>
    <Category>Resource Management</Category>
    <DSteward>
      <cntinfo>
        <cntperp>
           <cntper>Something</cntper>
        </cntperp>
        <cntaddr>
           <addrtype>mailing and physical</addrtype>
           <address>1 Smith Lane</address>
           <address></address>
           <city>Anywhere</city>
           <state>ST</state>
           <postal>12345</postal>
        </cntaddr>
        <cntemail>email@email.com</cntemail>
      </cntinfo>
    </DSteward>
  </DatStore>
</NPS_Info>

请原谅我笨拙的切割贴。 这个表中有几千行,但是,并非所有行都有第一个代码块中描述的xml元素(这是一个全局表,其中包含DB中所有表的描述,一些[Documentation]记录将包含非相关的xml对此操作不感兴趣)。

您可以使用XML数据修改语言(XML DML)

此代码将使用变量@XML的内容更改名为NPS_Info第一个节点的内容。

-- Delete everything in node NPS_Info
update YourTable
set XMLCol.modify('delete //NPS_Info[1]/*')

-- Insert @XML to node NPS_Info
update YourTable
set XMLCol.modify('insert sql:variable("@XML") into (//NPS_Info)[1]')

SE数据的工作样本

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM