最近做的项目,遇到如下问题:我有一个表:Dept 简单举例如下
ID, Name, ParentId
1 a 0
2 b 1
3 c 1
4 d 1
5 b01 2
6 b0101 5
7 c01 3
8 c0101 7
9 d01 4
10 d0101 9还有一个Msg 表,其中有个字段是Varchar类型 存储的是有权限看的部门ID
如下
ID Name Depts
1 msg 2,4
2 msg 3我有一个Staffer 表
其中有个Dept字段是Staffer对应的部门
现在我要做个查询,
就是查询某个Staffer对应的Msg表意思就是Msg里面存储的部门,只要Staffer的Dept字段是其或是其
子部门(子子部门...递归)就有权限,如staffer 对应 dept 为6,
那么Msg 中字段只要包含1,2,5,6(即dept为6的父部门--祖部门的 都可以查看到这样的查询语句我该怎么写?请教高手
ID, Name, ParentId
1 a 0
2 b 1
3 c 1
4 d 1
5 b01 2
6 b0101 5
7 c01 3
8 c0101 7
9 d01 4
10 d0101 9还有一个Msg 表,其中有个字段是Varchar类型 存储的是有权限看的部门ID
如下
ID Name Depts
1 msg 2,4
2 msg 3我有一个Staffer 表
其中有个Dept字段是Staffer对应的部门
现在我要做个查询,
就是查询某个Staffer对应的Msg表意思就是Msg里面存储的部门,只要Staffer的Dept字段是其或是其
子部门(子子部门...递归)就有权限,如staffer 对应 dept 为6,
那么Msg 中字段只要包含1,2,5,6(即dept为6的父部门--祖部门的 都可以查看到这样的查询语句我该怎么写?请教高手
解决方案 »
- 请问关于从手机端连接sql server express的问题
- SQL2000安装失败
- SQL Server的decimal所占字節數--儲存的格式是什麼?
- ap.net中调用有引号参数的存储过程问题
- Sqlserver2005安装issue
- 关于数据库的发布和订阅,快过年了,不解决老板不给放年假!
- 求一个关于工作日的SQL
- group by是做什么用的?给个例子看看?
- 怎样将MS SQL SERVER 6.5中的数据转到ORACLE 8中(编程的方法除外)
- 各视图或函数中的列名必须唯一。在视图或函数 'veb_book_publisher_category' 中多次指定了列名 'publisherId'。
- SQL语句的问题
- 提问一个sql语句,帮我看看!
declare @i int
set @i=1 declare @r table(id int,deep int)---取出ID为6的所有父
insert into @r(id,deep)
select ParentId, @i from Deptwhile (@@rowcount>0)
begin
set @i=@i+1 insert into @r(id,deep)
select ParentId, @i from Dept a
inner join @r b where b.id=a.id
where b.deep=@i-1
end
ID Name Deptid
1 aaa 5
2 bbb 6
3 ccc 9我要进行一个查询 查询Staffer可以查看的所有Msg只要Msg里的字段包含staffer.deptid的部门以及根部门,staffer就有权查看.如staffer.deptid 为6的时候1,2,5,6 都是6的根部门或者自身只要msg表里的depts字段包含这4个数,staffer都可以查询出来
insert dept
select 1,'a',0 union all
select 2,'b',1 union all
select 3,'c',1 union all
select 4,'d',1 union all
select 5,'b01',2 union all
select 6,'b0101',5 union all
select 7,'c01',3 union all
select 8,'c0101',7 union all
select 9,'d01',4 union all
select 10,'d0101',9
create table msg(id int,name varchar(10),depts varchar(200))
insert msg
select 1,'msg','2,4' union
select 2,'msg','3'go
create function dbo.f_tb(@id int)
returns @tb table(id int,pid int,levels int)
as
begin
declare @i int
set @i=0
insert into @tb
select ID,ParentId,@i from Dept where id=@id
while @@rowcount>0
begin
set @i=@i+1
insert into @tb
select a.ID,a.ParentId,@i from Dept a,@tb b where a.id=b.pid and levels=@i-1
end
return
end
go
select * from msg a where exists(
select 1 from dbo.f_tb(6) where charindex(','+cast(id as varchar)+',',','+a.Depts+',')>0
)
drop table msg,dept
drop function dbo.f_tb
===对应:参数6,dbo.f_tb(6)