读书人

求一字段处理语句解决方法

发布时间: 2012-01-28 22:06:13 作者: rapoo

求一字段处理语句
有一表A:
ID DeptName ParentID Depth RootID Child PrevID NextID OrderID
1 **公司  0   0   1 2 0 0 1
2 A部门   1   1  1 3 1 6 2
3 A1组  2   2  1 0 0 4 3
4 A2组  2   2  1 0 3 5 4
5 A3组  2   2  1 0 4 0 5
6 B部门   1   1  1 4 2 0 6
7 B1组  6   2  1 0 0 10 7
10 B2组  6   2  1 0 7 8 8
8 B3组  6   2  1 0 10 9 9
9 B4组  6   2  1 0 8 0 10


现需要增加一个字段 "DeptCode ",应该怎么写查询更新语句,填充如下表所示的值?

ID DeptName ParentID Depth RootID Child PrevID NextID OrderID DeptCode
1 **公司  0   0   1 2 0 0 1 001


2 A部门   1   1  1 3 1 6 2 001001
3 A1组  2   2  1 0 0 4 3 001001001
4 A2组  2   2  1 0 3 5 4 001001002
5 A3组  2   2  1 0 4 0 5 001001003
6 B部门   1   1  1 4 2 0 6 001002
7 B1组  6   2  1 0 0 10 7 001002001
10 B2组  6   2  1 0 7 8 8 001002002
8 B3组  6   2  1 0 10 9 9 001002003
9 B4组  6   2  1 0 8 0 10 001002004



[解决办法]
create table ta(ID int primary key, DeptName nvarchar(10), ParentID int,Depth int, RootID int, Child int,PrevID int,NextID int, OrderID int)
insert ta select 1, '**公司 ',0, 0,1, 2, 0, 0, 1
union all select 2, 'A部门 ', 1, 1, 1, 3, 1, 6, 2
union all select 3, 'A1组 ' , 2, 2, 1, 0, 0, 4, 3
union all select 4, 'A2组 ', 2, 2, 1, 0, 3, 5, 4
union all select 5, 'A3组 ', 2, 2, 1, 0, 4, 0, 5
union all select 6, 'B部门 ', 1, 1, 1, 4, 2, 0, 6
union all select 7, 'B1组 ', 6, 2, 1, 0, 0, 10, 7


union all select 10, 'B2组 ', 6, 2, 1, 0, 7, 8, 8
union all select 8, 'B3组 ', 6, 2, 1, 0, 10, 9, 9
union all select 9, 'B4组 ', 6, 2, 1, 0, 8, 0, 10

go

create function test_f(@ID int)
returns nvarchar(100)
as
begin
declare @s nvarchar(100),@i int

select @s=(select right( '000 '+rtrim(count(1)),3) from ta where ParentID=a.ParentID and OrderID!> a.OrderID),
@i=ParentID
from
ta a
where
ID=@ID
while exists(select 1 from ta where ID=@i)
select @s=
(select right( '000 '+rtrim(count(1)),3) from ta where ParentID=a.ParentID and OrderID!> a.OrderID)+@s,
@i=ParentID
from
ta a
where
ID=@i

return @s
end

go

select *,dbo.test_f(ID) from ta

--drop table ta
--drop function test_f


ID DeptName ParentID Depth RootID Child PrevID NextID OrderID
----------- ---------- ----------- ----------- ----------- ----------- ----------- ----------- ----------- ----------------------------------------------------------------
1 **公司 0 0 1 2 0 0 1 001
2 A部门 1 1 1 3 1 6 2 001001
3 A1组 2 2 1 0 0 4 3 001001001
4 A2组 2 2 1 0 3 5 4 001001002
5 A3组 2 2 1 0 4 0 5 001001003
6 B部门 1 1 1 4 2 0 6 001002
7 B1组 6 2 1 0 0 10 7 001002001
8 B3组 6 2 1 0 10 9 9 001002003
9 B4组 6 2 1 0 8 0 10 001002004
10 B2组 6 2 1 0 7 8 8 001002002

(所影响的行数为 10 行)

读书人网 >SQL Server

热点推荐