--求一触发器,自动维护树形数据的级数及路径!楼主stone66789()2005-10-20 10:40:27 在 MS-SQL Server / 基础类 提问
--求一触发器,自动维护树形数据的级数及路径!
--表结构如下:
item_id numeric --子id
item_de varchar(80) --子名称
parent_id numeric --父id
level_seq int --级别(树中的层数,树顶为1,向下递增)
path varchar(8000) --路径(从最顶层到本层的item_de相加,中间用_连接)
用户只录入前三项数据,要求在触发器中自动维护后两个字段的内容!
create table t(item_id numeric(20,0),item_de varchar(80),parent_id numeric(20,0),level_seq int,path varchar(8000))
insert into t(item_id,item_de,parent_id)
select 222,'aaa',0
union
select 324,'bbb',222
union
select 56,'ccc',324
union
select 543,'d',324
--要求插入上数据后,查询结果为
select * from t
/*
56 ccc 324 3 aaa_bbb_ccc
222 aaa 0 1 aaa
324 bbb 222 2 aaa_bbb
543 d 324 3 aaa_bbb_d
*/
执行如下语句,
update t
set item_de = 'dd'
where item_id = 324
查询数据
select * from t
结果如下
/*
56 ccc 324 3 aaa_dd_ccc
222 aaa 0 1 aaa
324 dd 222 2 aaa_dd
543 d 324 3 aaa_dd_d
*/
执行如下语句,
update t
set parent_id = 56
where item_id = 543
查询数据
select * from t
结果如下
/*
56 ccc 324 3 aaa_dd_ccc
222 aaa 0 1 aaa
324 dd 222 2 aaa_dd
543 d 56 4 aaa_dd_ccc_d
*/
----------------------------------------------------------
create proc vvv
as
set nocount on
declare @level int
declare @path nvarchar(300)
declare @first int
declare @tb table(tid int,lev int,path nvarchar(300))
set @level = 1
set @path = ''
select @first=item_id,@path = item_de from t where parent_id = 0
insert @tb select @first,@level,@path
--select * from @tb
while @@rowcount > 0
begin
set @level = @level +1
insert @tb
select t.item_id,@level,cast(tb.path as nvarchar(30)) + '_'+ cast(t.item_de as nvarchar(30))
from t join @tb as tb
on t.parent_id = tb.tid
where tb.lev = @level -1
end
update t set level_seq = nt.lev, path = nt.path from @tb as nt where t.item_id = nt.tid
create trigger ttt on t
after insert,update
as
exec vvv
exec vvv
http://topic.youkuaiyun.com/t/20051020/10/4338514.html
12:11 2010-5-6
----------------------------------------------------------
测试数据
------------------------------------------------------------
insert into t(item_id,item_de,parent_id)
select 222,'aaa',0
insert into t(item_id,item_de,parent_id)
select 324,'bbb',222
insert into t(item_id,item_de,parent_id)
select 56,'ccc',324
insert into t(item_id,item_de,parent_id)
select 543,'d',324
select * from t
/--------------
222 aaa 0 1 aaa
324 bbb 222 2 aaa_bbb
56 ccc 324 3 aaa_bbb_ccc
543 d 324 3 aaa_bbb_d
--------------------/
update t set item_de = 'abcde' where item_id = 222
select * from t
/--------------------------
222 abcde 0 1 abcde
324 bbb 222 2 abcde_bbb
56 ccc 324 3 abcde_bbb_ccc
543 d 324 3 abcde_bbb_d
-------------------------------/