您好,欢迎访问一九零五行业门户网

来自中油瑞飞的SQL笔试题20131202

1、有三张表,用户表,用户角色表,角色表,使用sql显示如下内容: 用户id,用户名,超级管理员,录入员,会计 也就是角色用逗号分隔。 解: 1、填充数据到表user select * from [user] insert into [northwind].[dbo].[user] ([id] ,[name]) values (1 ,zha
1、有三张表,用户表,用户角色表,角色表,使用sql显示如下内容:
用户id,用户名,超级管理员,录入员,会计
也就是角色用逗号分隔。
解:
1、填充数据到表user
select * from [user]
insert into [northwind].[dbo].[user]
([id]
,[name])
values
(1
,'zhaohy')
insert into [northwind].[dbo].[user]
([id]
,[name])
values
(2
,'zhangyy')
go
2、填充数据到表role
select * from [role]
insert into [northwind].[dbo].[role]
([id]
,[rolename])
values
(1
,'senior software engineer')
insert into [northwind].[dbo].[role]
([id]
,[rolename])
values
(2
,'project manager')
insert into [northwind].[dbo].[role]
([id]
,[rolename])
values
(3
,'ui disigner')
insert into [northwind].[dbo].[role]
([id]
,[rolename])
values
(4
,'tester')
go
3、填充数据到表role_user
select * from role_user
insert into [northwind].[dbo].[role_user]
([roleid]
,[userid])
values
(1
,1)
go
insert into [northwind].[dbo].[role_user]
([roleid]
,[userid])
values
(2
,1)
insert into [northwind].[dbo].[role_user]
([roleid]
,[userid])
values
(3
,1)
insert into [northwind].[dbo].[role_user]
([roleid]
,[userid])
values
(4
,2)
4、查询出来:
drop table #result;
select * into #result from (select u.id,u.name,ru.roleid,r.rolename from [user] u inner join role_user ru on ru.userid =u.id inner join [role] r
on ru.roleid=r.id) as t;
select * from #result;
select id,name, [rolename] = stuff((select ',' + [rolename] from #result t where id = #result.id for xml path('')) , 1 , 1 , '')
from #result
group by id ,name;
drop table #result;
输出结果:
其它类似信息

推荐信息