3

私はこのようなテーブルを持っています(実際には6000以上のレコードが含まれています)

IdIndustry   |   IndustryCode  |   IndustryName  |  ParentId
---------------------------------
1    |  IND    |   Industry  |   NULL
2    |  PHARM  |   Pharmacy  |   1
3    |  FIN    |   Finance   |   NULL
4    |  CFIN   |   Corporate |   3
5    |  CMRKT  |   Capital M |   4

DDL:

CREATE TABLE [dbo].[tblIndustryCodes](
    [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)

インサート:

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

そして、私はこのようなXMLファイルを生成したい(単純化されたツリーのような構造)

<IND>
      <PHARM>
      </PHARM>
</IND>
<FIN>
      <CFIN>
            <CMRKT>
            </CMRKT>
      </CFIN>
<FIN>

このテーブルにはテーブルに60000を超えるレコードがあるため、パフォーマンスが劇的に低下するため、再帰を使用したくありません。

この出力 XML を使用してリクエストを送信するので、出力を同じ形式で取得できれば幸いです。

さらに重要なことは、本質的に動的であることです。

4

1 に答える 1

1

結果を得るために一時テーブルを作成しているため、この手順を試してみてください。その効率についてはよくわかりません

create procedure get_path as begin
  DECLARE @cnt INT
  DECLARE @n INT
  DECLARE @tmpTable TABLE(id int, 
                indCode varchar(50), 
                indName varchar(100),
                parentId int,
                path varchar(500))

  insert @tmpTable 
          select [IdIndustry], [IndustryCode], [IndustryName], [ParentId],
          null from tbl

  select @cnt = count(*)  from @tmpTable where parentId is null
  update a set a.path = CONCAT(b.indName,'/',a.indName) from @tmpTable a, @tmpTable b where b.parentid is null and a.parentid = b.id
  select @n = count(*)  from @tmpTable where path is null
  while (@cnt < @n) begin
    update a set a.path = concat(b.path, '/', b.indName, '/', a.indName) from @tmpTable a, @tmpTable b where b.path is not null and a.parentid = b.id
    select @n = count(*) from @tmpTable where path is null
  end
  update @tmpTable set path = indName where parentid is null 
  select * from @tmpTable order by path
end
go

クエリ 1 :

exec get_path

結果

| ID | INDCODE |   INDNAME | PARENTID |                                  PATH |
-------------------------------------------------------------------------------
|  3 |     FIN |   Finance |   (null) |                               Finance |
|  4 |    CFIN | Corporate |        3 |                     Finance/Corporate |
|  5 |   CMRKT | Capital M |        4 | Finance/Corporate/Corporate/Capital M |
|  1 |     IND |  Industry |   (null) |                              Industry |
|  2 |   PHARM |  Pharmacy |        1 |                     Industry/Pharmacy |

お役に立てれば.....

SQL フィドル

于 2013-04-11T08:12:59.133 に答える