XML : tsql xml how to add default namespace and root path with inner join

objective: using Sql Server 2012, simplify the xml retrieval as much as possible. as starting point, specify default root path as well as default namespace.

details: the two tables are quite large, so using the indexes for the join is required. I've been unable to find an example that covers this scenario, although I've seen something similar when building an xml table using FOR XML PATH, type, Root=

SqlFiddle here: http://sqlfiddle.com/#!6/68df2/2/0

  --SqlFiddle here: http://sqlfiddle.com/#!6/68df2/2/0      Create Table t1 (id int, MoreFields varchar(10), DateAdded datetime)  create Table t2 (id int, data xml)    --objective: Using the sql select structure below, make the default root path= /Doc/DocumentProperties    insert into t1 values (1,'other data', '2015-10-30 19:30:21.953'),(2,'more data','2015-10-30 19:30:21.953')   insert into t2 values (1,'<Doc xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns="http://www.MyUrl.com" documentType="customDocument">    <DocumentProperties>      <DocumentID>1</DocumentID>      <Title>blah blah</Title>      <DateAdded>2015-10-30T15:30:21.9538615-04:00</DateAdded>      <VisitID>123456</VisitID>      <Patient>        <ID>9876</ID>        <FirstName>john</FirstName>        <LastName>doe</LastName>        <MiddleName />      </Patient>    </DocumentProperties>  </Doc>  '  )              ;with XMLNamespaces (DEFAULT 'http://www.MyUrl.com')             select       t1.id      ,t1.DateAdded      ,xmlDateAdded=t2.data.value('(/Doc/DocumentProperties/DateAdded)[1]', 'datetime')       ,Objective='Make /Doc/DocumentProperties the default root path, simplify node value retrieval'      --since everything is under DocumentProperties I want to do something like:       --,xmlDateAdded2    =t2.DateAdded   or      --,xmlDateAdded3    =?.value('/DateAdded','datetime')        --will be retrieving other node values as well.  from t1   inner join t2       on t1.id=t2.id   where t1.id=1--in real world criteria is multiple rows    drop table t1  drop table t2    

No comments:

Post a Comment