MSSQL: specifying targetNamespace with FOR XML, XMLSCHEMA

You have probably found that although you can specify the namespace to use for serializing to xml with FOR XML, there is no option for specifying the namespace of a generated xmlschema. Instead you get an autoincrementing uri for the users session, e.g. urn:schemas-microsoft-com:sql:SqlRowSet7

You can however assign that generated schema to an xml variable, and then simply use an xml dml to replace the value of the targetNamespace attribute. Here is a simple example, enjoy:

declare @x xml, @ns varchar(1024)
set @ns=’newNamespace’
set @x = (
 select *
 from (
  select top 0 1 as intId
 ) as t for xml auto, xmlschema
)
set @x.modify(‘declare namespace xsd = “http://www.w3.org/2001/XMLSchema“;
replace value of /xsd:schema[1]/@targetNamespace with sql:variable(“@ns”)’)
select @x

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s


%d bloggers like this: