Can you set a default namespace when using openxml in SQL SERVER

  Kiến thức lập trình

I have the following piece of sql

DECLARE @h int;
EXEC sp_xml_preparedocument @h OUTPUT, N'<root xmlns:a="urn:1"><a:Elem>T</a:Elem></root>', '<ns xmlns:a="urn:1" />';


--WITH XMLNAMESPACES (DEFAULT 'a')
SELECT * FROM openxml(@h, '/root/a:Elem')
      WITH (Col1 varchar(20) 'text()');
EXEC sp_xml_removedocument @h;

This gives me :
Col1
T

as expected.

I would like to get rid of the ‘a:’, something like

DECLARE @h int;
EXEC sp_xml_preparedocument @h OUTPUT, N'<root xmlns:a="urn:1"><a:Elem>T</a:Elem></root>', '<ns xmlns:a="urn:1" />';


WITH XMLNAMESPACES (DEFAULT 'a')
SELECT * FROM openxml(@h, '/root/Elem')
      WITH (Col1 varchar(20) 'text()');
EXEC sp_xml_removedocument @h;

But this does not work.

Yes, I could

  1. insert the namespaces or
  2. change the code the more modern using nodes, query, value instead of prepare, open, remove
    but

I have inherited a LOT of old SQL code, an I want to exploit this option before doing a lot of work.

SO: is there any way you can set a default namespace for openxml in sql server ?

New contributor

Peter Haastrup is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.

LEAVE A COMMENT