简体   繁体   中英

Column as content with FOR XML PATH query in SQL Server

I have a SQL query to get data from SQL Server 2012:

select dbo.TRIM(cfProj.cfProjId) as "cfProjId", 
       dbo.TRIM(cfProj.cfAcro) as "cfAcro",
       (SELECT cfLangCode as "@cfLangCode", cfTrans as "@cfTrans", cfProjTitle.cfTitle 
        FROM dbo.cfProjTitle
        WHERE dbo.cfProjTitle.cfProjId = dbo.cfProj.cfProjId
       FOR XML PATH('cfTitle'), type)  
from cfProj FOR XML PATH('cfProj')

This SQL returns data structure like:

<cfProj>
  <cfProjId>00001111</cfProjId>
  <cfAcro>222</cfAcro>
  <cfTitle cfLangCode="ru" cfTrans="h">
    <cfTitle>some title here</cfTitle>
  </cfTitle>
</cfProj>

But I want get XML structure without second nested "cfTitle" element:

<cfProj>
  <cfProjId>00001111</cfProjId>
  <cfAcro>222</cfAcro>
  <cfTitle cfLangCode="ru" cfTrans="h">some title here</cfTitle>
</cfProj>

Difference in this line: <cfTitle cfLangCode="ru" cfTrans="h">some title here</cfTitle>

Any ideas how I can get desirable result?

If you don't need multiple cfTitle elements, you can use marc_s solution, but if you do - you can try this:

select 
    p.cfProjId, 
    p.cfAcro,
    (
        select
            pt.cfLangCode as [@cfLangCode],
            pt.cfTrans as [@cfTrans],
            pt.cfTitle as [text()]
        from cfProjTitle as pt
        where pt.cfProjId = p.cfProjId
        for xml path('cfTitle'), type
    )
from cfProj as p
for xml path('cfProj')

sql fiddle demo

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM