Question

I have two XML Schemas where one depends on the other, and I'd like to create a typed XML column in SQL Server where the type is defined by one of my schemas (actually I have hundreds of schemas but in principle it's the same). When I create the column it accepts all the types defined in my entire schema collection, and I'd really like to limit the type for one column to just one of the types.

<schema targetnamespace="b">
   <simpleType name="b">
       <restriction base="string"><pattern value="(0[1-9])"/></restriction>
   </simpleType>
</schema>

<schema targetnamespace="a" xmlns:b="b">
   <element name="b" type="b:b" />
   <complexType name="aType">
      <sequence>
         <element ref="b"/>
      </sequence>
   </complexType>
   <element name="a" type="aType"/>
</schema>

So first I create the schema collection with

CREATE XML SCHEMA COLLECTION Foo AS N'<above schemas>'

and then I create the column with

ALTER TABLE FooTable ADD fooCol [xml] (Document [Foo])

Now I can insert values into the column of XML types "a" as well as "b", but I'd really like to limit the column type to just "a".

Is there any way of achieving that, short of hand-writing customized schema collections for each different type?

Updated:

Regarding the check constraint suggested - according to http://blogs.msdn.com/b/denisruc/archive/2006/08/22/713342.aspx the check constraint would then be something along the lines of

CREATE FUNCTION dbo.checkTopElmntIsTypeA(@x XML(MySchemaCollection))
RETURNS bit
AS
BEGIN
    RETURN ~(@x.exist('/a:a'))
END
go

-and the table definition to limit content of a column to XML type a

CREATE TABLE T(xmlCol XML(MySchemaCollection)
    CHECK (1 = dbo.checkTopElmntIsTypeA(xmlCol)))
go

I guess that could do, even if it's not quite as nice. :-)

No correct solution

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top