0

I have XML like this, stored in an XML field in sql server:

<TableSpec
   xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
   xmlns:xsd="http://www.w3.org/2001/XMLSchema"
   xmlns="custom_schema_name"
   ID="66912703-1201-457C-A37B-84D446B6C043"
   Name="Some name"
 >
  <Fields>
    <ForeignKeyField Name="SOMETABLEID" Required="true" ForeignTable="SOMETABLE"/>
    <GuidField Name="FIELD1" Required="true" />
    <DateField Name="FIELD2" Required="true" />
  </Fields>
</TableSpec>

I want to select the "Name" of every Field that is not a Foreign Key Field.

Given this example, I'd like my result set to be:

FIELD1
FIELD2

How can I do that?

1 Answer 1

1

Here is some pseudo code. You will have to modify this for your specific sample.

Edit: I modified the code to reflect your namespace.

declare @x xml
set @x = 
'<TableSpec
   xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
   xmlns:xsd="http://www.w3.org/2001/XMLSchema"
   xmlns="custom_schema_name"
   ID="66912703-1201-457C-A37B-84D446B6C043"
   Name="Some name">
  <Fields>
    <ForeignKeyField Name="SOMETABLEID" Required="true" ForeignTable="SOMETABLE"/>
    <GuidField Name="FIELD1" Required="true" />
    <DateField Name="FIELD2" Required="true" />
  </Fields>
</TableSpec>'

;WITH XMLNAMESPACES ('custom_schema_name' as custom_schema_name)
select
    x.i.value('@Name','varchar(256)'),
    x.i.value('local-name(.)','varchar(256)')
from @x.nodes('/custom_schema_name:TableSpec/custom_schema_name:Fields/*') x(i)
where x.i.value('local-name(.)','varchar(256)') <> 'ForeignKeyField'
Sign up to request clarification or add additional context in comments.

1 Comment

That worked flawlessly. Thank you very much! When I have to query XML from SQL I feel like I'm trying to write a poem with a sponge - it just doesn't make sense.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.