为联合查询设置变量

时间:2014-11-20 21:35:59

标签: sql variables sql-server-2008-r2 union

我有以下联合查询,它通过15个级别;我只展示了三个,所以你明白了。我想在输入顶部设置变量,因此我不需要每次都更改15x3标准。变量我想在顶部设置一次以适用于所有变量: pyh_per_cc pyh_tc_batch pyh_no01(注意:这是一个' IN'标准)

有办法做到这一点吗?我正在使用SQL Server Mgmt Studio 2008 R2,以防万一。 提前谢谢!

select hr_pe_id, pyh_no01 pyh_no, pyh_amt01 pyh_amt
from pyh_hst_dtl 
where pyh_no01 <> 0
and pyh_per_cc = '1301001'
and pyh_tc_batch = 'P1301001'
and pyh_no01 in ('2100','2101','2105','2108','2113','2115','2117','2118','2119')
union
select hr_pe_id, pyh_no02 pyh_no, pyh_amt02 pyh_amt
from pyh_hst_dtl
where pyh_no02 <> 0
and pyh_per_cc = '1301001'
and pyh_tc_batch = 'P1301001'
and pyh_no02 in ('2100','2101','2105','2108','2113','2115','2117','2118','2119')
union
select hr_pe_id, pyh_no03 pyh_no, pyh_amt03 pyh_amt
from pyh_hst_dtl
where pyh_no03 <> 0
and pyh_per_cc = '1301001'
and pyh_tc_batch = 'P1301001'
and pyh_no03 in  ('2100','2101','2105','2108','2113','2115','2117','2118','2119')
order by hr_pe_id

1 个答案:

答案 0 :(得分:0)

抱歉,错过了你两次测试相同字段的值。

这会有用吗?

CREATE TABLE #pyh_nos(pyh_no char(4));

insert into #pyh_nos values ('2100');
insert into #pyh_nos values ('2101');
insert into #pyh_nos values ('2105');
insert into #pyh_nos values ('2108');
insert into #pyh_nos values ('2113');
insert into #pyh_nos values ('2115');
insert into #pyh_nos values ('2117');
insert into #pyh_nos values ('2118');
insert into #pyh_nos values ('2119');

select 
hr_pe_id, pyh_no01 pyh_no, pyh_amt01 pyh_amt
from 
pyh_hst_dtl h left outer join
#pyh_nos p1 on 
pyh_no01 = p1.pyh_no left outer join
#pyh_nos p2 on 
pyh_no02 = p2.pyh_no
...
left outer join
#pyh_nos p15 on 
pyh_no15 = p15.pyh_no
where  
pyh_per_cc = '1301001'
and pyh_tc_batch = 'P1301001' and
(p1.pyh_no is not null or
...
p15.pyh_no is not null)