--用户表
id name
1 张三
2 李四
3 王五
4 肖六--权限表 (查看权限为varchar型)
id 查看权限
1 1,2,3
要求: 权限表id为1的情况下,查询出张三、李四、王五
类似: select a.name from 用户表 a,查看权限 b
where a.id in(b.查看权限) and b.id=1
id name
1 张三
2 李四
3 王五
4 肖六--权限表 (查看权限为varchar型)
id 查看权限
1 1,2,3
要求: 权限表id为1的情况下,查询出张三、李四、王五
类似: select a.name from 用户表 a,查看权限 b
where a.id in(b.查看权限) and b.id=1
where charindex(',' + cast(m.id as varchar) + ',' , ',' + n.查看权限 + ',') > 0 and n.id = 1
insert into 用户表 values(1 ,'张三')
insert into 用户表 values(2 ,'李四')
insert into 用户表 values(3 ,'王五')
insert into 用户表 values(4 ,'肖六')
create table 权限表(id int,查看权限 varchar(20))
insert into 权限表 values(1 ,'1,2,3')
go--方法一
select m.* from 用户表 m , 权限表 n
where charindex(',' + cast(m.id as varchar) + ',' , ',' + n.查看权限 + ',') > 0 and n.id = 1
/*
id name
----------- ----------
1 张三
2 李四
3 王五(所影响的行数为 3 行)
*/--方法二
select m.* from 用户表 m , 权限表 n
where ',' + n.查看权限 + ',' like '%,' + cast(m.id as varchar) + ',%' and n.id = 1
/*
id name
----------- ----------
1 张三
2 李四
3 王五(所影响的行数为 3 行)
*/drop table 用户表,权限表
returns @temp table(F1 varchar(100))
as
begin
declare @ch as varchar(100)
set @SourceSql=@SourceSql+@StrSeprate
while(@SourceSql<>'')
begin
set @ch=left(@SourceSql,charindex(',',@SourceSql,1)-1)
insert @temp values(@ch)
set @SourceSql=stuff(@SourceSql,1,charindex(',',@SourceSql,1),'')
end
return
end
----调用
select * from dbo.f_splitstr('1,2,3',',')
--结果:
1
2
3
4
然后再查询
id name
1 张三
2 李四
3 王五
4 肖六--权限表 (查看权限为varchar型)
id 查看权限 完成时间 URL
1 1,2,3 2010-05-06 http://www.....
要求结果(权限表id=1):
id 查看人 完成时间 URL
1 张三、李四、王五 2010-05-06 http://www.....
insert into 用户表 values(1 ,'张三')
insert into 用户表 values(2 ,'李四')
insert into 用户表 values(3 ,'王五')
insert into 用户表 values(4 ,'肖六')
create table 权限表(id int,查看权限 varchar(20))
insert into 权限表 values(1 ,'1,2,3')
go
create view v_tb
as
select n.id , m.name
from 用户表 m , 权限表 n
where ',' + n.查看权限 + ',' like '%,' + cast(m.id as varchar) + ',%' and n.id = 1 if object_id('fc_unionstr') is not null
drop function fc_unionstr
go
create function fc_unionstr
(
@id int
)
returns varchar(1000)
begin
declare @str varchar(1000)
set @str=''
select @str=@str+','+name
from v_tb
where id=@id
set @str=stuff(@str,1,1,'')
return @str
end
select id,dbo.fc_unionstr(id) as 查看权限
from v_tb
group by id这是我哥们贞冬木解决的,谢谢他