FOR XML列名称'Value / @ json:ValueType'缺少XML名称空间前缀'json'声明

时间:2018-07-02 14:02:16

标签: sql json sql-server xml xml-namespaces

我正在一个项目中,我正在编写的存储过程正在生成XML格式的输出。我想向“主”节点添加名称空间,并向子节点添加JSON ValueType。下面是我的代码:

--- Fake tables in stored procedure
create table #Cdetails(cid int, cidtype varchar(5), name varchar(5), age int)

insert into #Cdetails
values (1001, 'N', 'John', 12), (1002, 'U', 'Rick', 19),
       (1003, 'N', 'Diane', 25), (1004, 'N', 'Kippy', 26)

--Output of stored procedure 

create table #final(cid int, cidtype varchar(5), xml_data xml)

insert into #final
    select
        cid = c1.cid,
        cidtype = c1.cidtype,
        case 
           when c1.cidtype = 'N' 
              then (select 
                        'Value/@json:ValueType'='Number',
                        ID = cd1.cid,
                        details = (select  
                                       cd1.name, cd1.age
                                   for xml path(''), type)
                    from  
                        #Cdetails cd1
                    where 
                        cd1.cid = c1.cid
                    for xml path('Main'))
           when c1.cidtype = 'N' 
              then (select 
                        ID = cd1.cid,
                        details = 'Null'            
                    from 
                        #Cdetails cd1
                    where 
                        cd1.cid = c1.cid
                    for xml path('Main')) 
        end as 'xml_data'
    from 
        #Cdetails c1 

;WITH XMLNAMESPACES ('http://www.integround.com/json' as json)  
SELECT * 
FROM #final 
WHERE xml_data IS NOT NULL
FOR XML PATH('Main')

drop table #Cdetails, #final

在此过程中,基于CIDType条件生成XML。所以我当前的输出是:

enter image description here

我想将名称空间添加到“主”节点,并将JSON属性添加到子节点。

错误

  

FOR XML列名称“ Value / @ json:ValueType”缺少XML名称空间前缀“ json”声明。

所需的输出:

enter image description here

有帮助吗?!

1 个答案:

答案 0 :(得分:1)

XML Construction可以帮助您吗?

DECLARE @cdetails table(
  cid INT, cidtype VARCHAR(5), name VARCHAR(5), age INT
);

INSERT INTO @cdetails VALUES
  (1001, 'N', 'John', 22), (1002, 'U', 'Rick', 21),
  (1003, 'N', 'Diane', 25), (1004, 'N', 'Kippy', 26);

SELECT
  cid, cidtype,
  CAST('' AS XML).query('
<Main xmlns:json="http://www.samplenamespace.com/json">
  <ID json:ValueType="Number">{sql:column("cid")}</ID>
  {
    if( sql:column("cidtype")="N" ) then
      <details>
        <name>{sql:column("name")}</name>
        <age>{sql:column("age")}</age>
      </details>
    else <details>Null</details>
  }
</Main>
  ')
FROM @cdetails;