从分层表数据(T-SQL)生成结构化(xml)文档

前端之家收集整理的这篇文章主要介绍了从分层表数据(T-SQL)生成结构化(xml)文档前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我有这样的表(简化):
  1. ID | Name | Parent
  2. ---------------------------------
  3. 1 | IND | NULL
  4. 2 | INS | 5
  5. 3 | CON | NULL
  6. 4 | AUT | 1
  7. 5 | FIN | NULL
  8. 6 | PHA | 1
  9. 7 | CFIN | 5
  10. 8 | CMRKT | 7

DDL:

  1. CREATE TABLE [dbo].[tblIndustryCodes](
  2. [IdIndustry] [int] IDENTITY(1,1) NOT NULL,[IndustryCode] [nvarchar](5) NULL,[IndustryName] [nvarchar](50) NULL,[ParentId] [int] NULL,CONSTRAINT [PK_tblIndustryCodes] PRIMARY KEY CLUSTERED ( [IdIndustry] ASC))

插入内容

  1. INSERT INTO [tblIndustryCodes]
  2. ([IndustryCode],[IndustryName],[ParentId])
  3. VALUES
  4. ('IND','Industry',NULL),('PHARM','Pharmacy',1),('FIN','Finance',('CFIN','Corporate Finance',3),('CMRKT','Capital Markets',4)

我想从它生成一个xml文件,它根据父ID进行结构化

像这样(简化)

  1. <IND>
  2. <AUT>
  3. <PHA>
  4. <CON>
  5. <FIN>
  6. <CFIN>
  7. <CMRKT>

我相信它的完成可能是某种类型的递归或类似的东西,但我不知道如何.任何帮助是极大的赞赏!

编辑:它是sql Server Express 2008

我真的不在乎它是否是有效的XML,因为我只使用它来填充树视图控件.

edit2:我可能会使用“FOR XML EXPLICIT”,但是当没有固定的树最大深度时,我真的不理解语法.

edit3:为了更容易理解任务,我为表添加了DDL

解决方法

根据Recep的回答(见评论),我为这个问题创建了以下解决方案:

1.创建递归函数

  1. CREATE function SelectChild(@key as int)
  2. returns xml
  3. begin
  4. return (
  5. select
  6. IdIndustry as "@key",ParentId as "@parentkey",IndustryCode as "@Code",IndustryName as "@Name",dbo.SelectChild(IdIndustry)
  7. from tblIndustryCodes
  8. where ParentId = @key
  9. for xml path('record'),type
  10. )
  11. end

2.构建一个调用函数的SELECT语句

  1. SELECT
  2. IdIndustry AS "@key",'' AS "@parentkey",dbo.SelectChild(IdIndustry)
  3. FROM dbo.tblIndustryCodes
  4. WHERE ParentId is null
  5. FOR XML PATH ('record')

无论树实际有多深,这都会创建一个分层XML:

  1. <record key="1" parentkey="" Code="IND" Name="Industry">
  2. <record key="2" parentkey="1" Code="AUTO" Name="Automotive" />
  3. <record key="3" parentkey="1" Code="PHARM" Name="Pharmaceuticals" />
  4. </record>
  5. <record key="4" parentkey="" Code="FIN" Name="Finance">
  6. <record key="5" parentkey="4" Code="CFIN" Name="Corporate Finance">
  7. <record key="6" parentkey="5" Code="CMRKT" Name="Capital Markets" />
  8. </record>
  9. </record>
  10. <record key="7" parentkey="" Code="CON" Name="Cosulting">
  11. <record key="8" parentkey="7" Code="IMPL" Name="Implementation" />
  12. <record key="9" parentkey="7" Code="STRAT" Name="Strategy" />
  13. </record>

猜你在找的MsSQL相关文章