要创建一个用来查询的存储过程,数据库里有二十四张表,表名都是以月份命名的tabyyyymm(如tab200703),选择日期查询时可以是查询某一个月的,也可以跨月份的查询,比如查询2007年2月份至6月份的数据,已经有高手指点了,
但还有个问题
就是想在存储过程里添加个变量,接受其他条件查询,表里有name 和id两个字段。根据name 去查id。这样写不对
create table tab200701(id int,name char(10))
insert into tab200701 select 1,aa
create table tab200702(id int,name char(10))
insert into tab200702 select 2,bb
create table tab200703(id int,name char(10))
insert into tab200703 select 3,cc
create table tab200704(id int,name char(10))
insert into tab200704 select 4,dd
go
create proc usp_test
@begin varchar(06),
@end varchar(06)= ' ',
@name varchar(50)
AS
if @end= ' '
set @[email protected]
declare @sql varchar(8000)
set @sql= ' '
select @[email protected][email protected]+ ' union all select * from [ '+name+ '] ' from sysobjects
where right(name,6) > = @begin
and right(name,6) <[email protected]
and name like 'tab% '
and len(name)=9
and xtype= 'u '
set @sql= stuff(@sql,1,11, ' ')
exec(@sql)
print @sql
GO
exec usp_test '200701 ', '200702 ', 'where name= 'vicky ' '
------解决方案--------------------
create proc usp_test
@begin varchar(06),
@end varchar(06)= ' ',
@name varchar(50)
AS
if @end= ' '
set @[email protected]
declare @sql varchar(8000)
set @sql= ' '
select @[email protected]+ ' union all select * from [ '+name+ '] ' from sysobjects
where right(name,6) > = @begin
and right(name,6) <[email protected]
and name like 'tab% '
and len(name)=9
and xtype= 'u '
set @sql= stuff(@sql,1,11, ' ') + @name
exec(@sql)
print @sql
GO
exec usp_test '200701 ', '200702 ', 'where name= ' 'vicky ' ' '
------解决方案--------------------
如果想where对每个表生效就要加到每个表的后面
select @[email protected]+ ' union all select * from [ '+name+ '] '[email protected] from sysobjects