27,579
社区成员
发帖
与我相关
我的任务
分享
--更新语句
;WITH CTE AS(
SELECT code,content,CAST(content AS VARCHAR(8000))FCONTENT
FROM DEPT
WHERE LEN(code)<3
UNION ALL
SELECT T1.code,T1.content,T2.FCONTENT+'/'+T1.content
FROM DEPT T1
JOIN CTE T2 ON LEFT(T1.code,LEN(T2.code))=T2.code AND LEN(T1.code)=LEN(T2.code)+2
)
UPDATE T1
SET FCONTENT=T2.FCONTENT
FROM DEPT T1
JOIN CTE T2 ON T1.code=T2.code
--查看结果
SELECT * FROM DEPT
create table DEPT
(code varchar(20),content varchar(20),FCONTENT varchar(50))
insert into DEPT(code,content)
select '1','XX公司' union all
select '101','A部门' union all
select '10101','甲组' union all
select '102','B部门' union all
select '10201','甲组' union all
select '1020101','一班'
-- 创建函数
create function dbo.fn_AutoGenFCONTENT
(@x varchar(20))
returns varchar(50)
as
begin
declare @y varchar(50)
while(len(@x)>0)
begin
select @y=content+isnull('/'+@y,'')
from DEPT
where code=@x
select @x=left(@x,case when len(@x)-2<0 then 0 else len(@x)-2 end)
end
return @y
end
-- 更新
update DEPT
set FCONTENT=dbo.fn_AutoGenFCONTENT(code)
-- 结果
select * from DEPT
/*
code content FCONTENT
-------------------- -------------------- ----------------------------
1 XX公司 XX公司
101 A部门 XX公司/A部门
10101 甲组 XX公司/A部门/甲组
102 B部门 XX公司/B部门
10201 甲组 XX公司/B部门/甲组
1020101 一班 XX公司/B部门/甲组/一班
(6 row(s) affected)
*/