2012-01-15 73 views
4

在下面的表格:SQL Server 2008中的发现和XML列替换元素

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 protected]</cntemail> 
     </cntinfo> 
    </DSteward> 
    </DatStore> 
</NPS_Info> 

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

回答

3

您可以使用XML Data Modification Language (XML DML)

此代码将更改名为NPS_Info与可变@XML的内容第一节点的内容。

-- 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 Data

+0

嘿感谢!当我尝试该代码块时,首先使用:dbname declare @T dbo.gdb_items(Documentation xml)我收到以下内容:Msg 102,Level 15,State 1,Line 5 'Documentation'附近的语法不正确。 Msg 1087,Level 15,State 2,Line 7 必须声明表变量“@T”。 消息1087,级别15,状态2,行54 必须声明表变量“@T”。 Msg 1087,Level 15,State 2,Line 57 必须声明表变量“@T”。 Msg 1087,Level 15,State 2,Line 61 必须声明表变量“@T”我必须丢失一些非常明显的东西 – tpcolson 2012-01-15 20:02:06

+1

没关系....真的很明显。我看到你在SE做了什么,并改变了在非临时环境中工作。谢谢一堆! – tpcolson 2012-01-15 20:08:02