将查询条件作为结果输出,求一存储过程
假设:(我说的是假设,如有雷同,那不意思,也有可能是巧合!!!)
-----------------testa-----------------------------------
drop table testa
go
create table testA(id int,nm varchar(20),cityid int ,citynm varchar(50),rearid int ,areanm varchar(50))
insert into testA select 1,'东京A',01,'东京热',1001,'东京热1'
union all
select 2,'东京B',01,'东京热',1001,'东京热1'
union all
select 3,'东京C',01,'东京热',1001,'东京热1'
union all
select 4,'加勒比A',02,'加勒比',1002,'asd'
union all
select 5,'加勒比B',02,'加勒比',1002,'asd'
union all
select 6,'加勒比C',02,'加勒比',1002,'asd'
union all
select 7,'一本道A',03,'一本道',1002,'asd'
union all
select 8,'一本道B',03,'一本道',1002,'asd'
union all
select 9,'一本道C',03,'一本道',1002,'asd'
select * from testa
drop table testB
go
create table testB(id int, nm varchar(50),cityid int,rearid int,nmid int)
insert into testB select 1,'苍井空',1,1001,1
union all
select 2,'武藤兰',1,1001,1
union all
select 3,'饭岛爱',1,1001,1
union all
select 4,'小泽玛莉亚',1,1001,1
union all
select 5,'啊啊啊',2,1002,2
union all
select 6,'嗷嗷啊',4,1002,4
select * from testB
select a.nm as '子公司',a.areanm as '子子公司',a.citynm as '公司',b.nm as 'star' from testA a join testB b on a.id = b.nmid
----------------------------------------------
子公司子子公司公司star
东京A东京热1东京热苍井空
东京A东京热1东京热武藤兰
东京A东京热1东京热饭岛爱
东京A东京热1东京热小泽玛莉亚
东京B东京热1东京热啊啊啊
加勒比Aasd加勒比嗷嗷啊
select a.nm as '子公司',a.citynm as '公司',b.nm as 'star' from testA a join testB b on a.id = b.nmid
where b.nmid = 1
------------得到以nmid的value东京A作为列头-----------------------
子公司公司star
东京A东京热苍井空
东京A东京热武藤兰
东京A东京热饭岛爱
东京A东京热小泽玛莉亚
select a.areanm as '子子公司',a.citynm as '公司',b.nm as 'star' from testA a join testB b on a.id = b.nmid
where b.rearid = 1001
------------得到以rearid 的value东京热1作为列头-----------------------
子子公司公司star
东京热1东京热苍井空
东京热1东京热武藤兰
东京热1东京热饭岛爱
东京热1东京热小泽玛莉亚
create proc pr_name(@str varchar(100))
as
begin
exec('select a.nm as ''子公司'',a.citynm as ''公司'',b.nm as ''star''
from testA a join testB b on a.id = b.nmid where '+@str)
end
exec pr_name 'b.rearid = 1001'
[解决办法]
create proc pr_name(@str varchar(100))
as
begin
if @str like '%nmid%'
exec('select a.nm as ''子公司'',a.citynm as ''公司'',b.nm as ''star''
from testA a join testB b on a.id = b.nmid where '+@str)
else if @str like '%rearid %'
exec('select a.areanm as ''子子公司'',a.citynm as ''公司'',b.nm as ''star''
from testA a join testB b on a.id = b.nmidwhere '+@str)
end
exec pr_name 'b.rearid = 1001'