Ask Your Question

Revision history [back]

click to hide/show revision 1
initial version

You can modify or add an XML namespace in SQL Server by using the WITH XMLNAMESPACES statement. This statement specifies the namespaces to be used in the XML query or modification.

For example:

DECLARE @xml XML = '<root><book><title>Hello World</title></book></root>';

-- Adding a namespace
SET @xml = @xml.modify('declare namespace myns="http://example.com"; 
    insert (<myns:book><myns:title>Goodbye World</myns:title></myns:book>) as last into (/root)[1]');

-- Modifying a namespace
SET @xml = @xml.modify('declare default element namespace "http://new.example.com";
    replace value of (/root/book/title)[1] with "New Title"');

-- Querying with a namespace
;WITH XMLNAMESPACES ('http://example.com' AS ns)
SELECT @xml.value('(/root/ns:book/ns:title)[1]', 'varchar(100)') AS Title;

In this example, the declare namespace statement is used to add a new myns namespace, and the declare default element namespace statement is used to modify the default namespace. When querying the XML, the WITH XMLNAMESPACES statement is used to specify the namespace to be used.