码迷,mamicode.com
首页 > 数据库 > 详细

SQL批量更新具有树形结构表Path字段

时间:2014-07-21 09:29:07      阅读:352      评论:0      收藏:0      [点我收藏+]

标签:style   blog   http   color   2014   io   

bubuko.com,布布扣

如上图所示,需要更新该表中Path字段,如ID=14的Path值:-1,ID=17的Path值:-1.14,ID=20的Path值:-1.14.18.19

步骤1、创建函数

Create FUNCTION  [dbo].[F_Org]
(    
@id int 
)
RETURNS TABLE 
AS
RETURN 
(
with testTable 
as(
select UpperID from Core_DeptInfo  
where ID=@id union all 
select Core_DeptInfo.UpperID from Core_DeptInfo,testTable 
where Core_DeptInfo.ID=testTable .UpperID)
 select UpperID  from testTable   
)

步骤2、循环执行SQL

declare @minId int 
declare @maxId int 
declare @result nvarchar(50)
declare @count int
select  @minId = MIN(id) from Core_DeptInfo
select  @maxId = MAX(id) from Core_DeptInfo

WHILE @maxId >=@minId
BEGIN
    select @count = COUNT(1) from Core_DeptInfo where  ID=@maxId;
    if @count=1
    begin
        select @result = (select  CONVERT(nvarchar(50),UpperID) +.  from dbo.F_Org(@maxId) order by UpperID    for xml path(‘‘)  )  
        set @result = LEFT(@result,LEN(@result)-1)  
        update Core_DeptInfoExtend set Path=@result where ID=@maxId
    end      
    SET @maxId = @maxId -1
END 

SQL批量更新具有树形结构表Path字段,布布扣,bubuko.com

SQL批量更新具有树形结构表Path字段

标签:style   blog   http   color   2014   io   

原文地址:http://www.cnblogs.com/BruceGoGo/p/3856232.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!