id one two three four five
1 资源
2 资源 工具
3 资源 工具 产品
4 资源 工具 成品
5 资源 研发id deptlevel deptname username
1 two(a表中列名) 工具 admin
2 three(a表中列名) 成品 sa这是两表结构,没有关系
怎么求出两表数据根据用户名
例:根据admin用户名查找 (a表中id为2,3,4的数据查找出来)
1 资源
2 资源 工具
3 资源 工具 产品
4 资源 工具 成品
5 资源 研发id deptlevel deptname username
1 two(a表中列名) 工具 admin
2 three(a表中列名) 成品 sa这是两表结构,没有关系
怎么求出两表数据根据用户名
例:根据admin用户名查找 (a表中id为2,3,4的数据查找出来)
create table ta(id int,one varchar(10),two varchar(10),three varchar(10),four varchar(10),five varchar(10))
insert into ta
select 1,'资源','','','','' union all
select 2,'资源','工具','','','' union all
select 3,'资源','工具','产品','','' union all
select 4,'资源','工具','产品','','' union all
select 5,'资源','研发','','' ,''
create table tb(id int,deptlevel varchar(10),deptname varchar(10),username varchar(10))
insert into tb
select 1,'two','工具','admin' union all
select 1,'three','成品','sa'Create proc G(@name varchar(10))
as
begindeclare @level varchar(10)
declare @dept varchar(10)
declare @sql varchar(100)select @level = deptlevel,@dept = deptname from tb where username = @name
set @sql = 'select * from ta where ' + @level + ' = ''' + @dept + ''''
exec(@sql)endexec G 'admin'/*
id one two three four five
----------- ---------- ---------- ---------- ---------- ----------
2 资源 工具
3 资源 工具 产品
4 资源 工具 产品 (所影响的行数为 3 行)
*/
if OBJECT_ID('tb') is not null
drop table tb
go
create table tb(id int,one varchar(4),two varchar(4),three varchar(4),four varchar(4),five varchar(4))
insert into tb
select 1, '资源','','' ,'','' union all
select 2, '资源', '工具','','','' union all
select 3, '资源', '工具', '产品','','' union all
select 4, '资源', '工具', '成品','','' union all
select 5, '资源', '研发','','',''
select * from tb if OBJECT_ID('ta') is not null
drop table ta
go
create table ta(id int,deptlevel varchar(10),deptname varchar(4),username varchar(10))
insert into ta
select 1, 'two', '工具' ,'admin' union all
select 2, 'three','成品', 'sa'declare @username varchar(10),
@sql varchar(8000)
set @username='admin'
set @sql=''
select @sql=QUOTENAME(deptlevel)+'= '''+ltrim(deptname)+''''
from ta
where username=@username
exec('select id from tb where '+@sql)id
2
3
4
不用存储过程,就一条SQL怎么写
还是不太明白 能直接用一条select语句表述吗
select @sql='select * from ta where '+convert(varchar(20),deptlevel)+'='''+convert(varchar(20), deptname)+''''
from tb where username ='admin'
exec (@sql)
select QUOTENAME(deptlevel)+'= '''+ltrim(deptname)+''''
from ta where username='admin'用一条sql语句是这样吗?但是会报错耶
@sql varchar(8000)
set @sql=''
select @sql=QUOTENAME(deptlevel)+'= '''+ltrim(deptname)+''''
from ta
where username='admin'
exec('select * from tb left join tc on tb.id=tc.id
where ' +@sql )