MSSQLServer数据库大量数据按月份分表、存储过程指定时间段跨表分页查询

比较完善的大量数据分表功能代码,包含创建数据库、生成数据、测试结果。适合初学分表者使用。
数据按照每个月创建一个数据表,通过存储过程输入参数,按照指定日期跨表查询数据,并且可以分页查询。
有如下表:
table_20180101
table_20180201 table_20180301
table_20180401
CREATE TABLE [dbo].[table_20180101](
	[id] [bigint] IDENTITY(180101000000000,1) NOT NULL,
	[info] [varchar](25) NULL,
	[time] [datetime] NOT NULL
) ON [PRIMARY]
CREATE TABLE [dbo].[table_20180201](
	[id] [bigint] IDENTITY(180201000000000,1) NOT NULL,
	[info] [varchar](25) NULL,
	[time] [datetime] NOT NULL
) ON [PRIMARY]

每个表中生成一百万条数据,用存储过程的方式跨表查询指定时间的数据。

create proc [dbo].[Proc_MultiTableData]

(
@FromTime datetime,
@ToTime datetime,
@TimeColumnName varchar(200),
@PageIndexFrom bigint,
@PageIndexTo bigint,
@IsMonthOffset bit
)
as
begin
declare @FromTimeRefer datetime
declare @ToTimeRefer datetime
SELECT @FromTimeRefer = CONVERT(varchar(20),DATEADD(dd,-DAY(@FromTime)+1,@FromTime),120)
SELECT @ToTimeRefer = CONVERT(varchar(20),DATEADD(ms,-3,DATEADD(mm,DATEDIFF(m,0,@ToTime)+1,0)),120)


if @IsMonthOffset = 0
begin
set @FromTimeRefer = @FromTime
set @ToTimeRefer = @ToTime
end

DECLARE MyCursor CURSOR For select name from sys.tables where name in 
( select name from sys.tables where name like 'table_%' and ISDATE( right(name,8))= 1  ) 
and CONVERT(datetime,CAST(right(name,8) AS datetime),120) >= @FromTimeRefer 
and CONVERT(datetime,CAST(right(name,8) AS datetime),120) <=@ToTimeRefer

DECLARE @tablename varchar(255)
DECLARE @SQL varchar(max)
set @tablename = ''
set @SQL = ''

OPEN MyCursor
FETCH NEXT FROM  MyCursor INTO @tablename
WHILE @@FETCH_STATUS =0
BEGIN
set @SQL=@SQL+' union all select * from '+@tablename +' where '+@TimeColumnName+'>='''
+convert(varchar(20), @FromTime,120) + ''' and '+@TimeColumnName+'<='''+ convert(varchar(20),@ToTime,120) +''''
FETCH NEXT FROM  MyCursor INTO @tablename
END    
CLOSE MyCursor
DEALLOCATE MyCursor

set @SQL= substring(@SQL,12,len(@SQL));


exec(@SQL)

---调试信息
select @FromTimeRefer as FromTimeRefer 
select @ToTimeRefer as ToTimeRefer
select @SQL as aSQL

end


我自己参考别人写的sql代码。目前修改的比较完善。
以上代码支持输入参数按照时间段跨表查询,我去掉了分页查询功能,完整的实例中包含分页查询功能。如果需要完整的实例,可以到我csdn页面里下载,实例里包括创建数据库,生成数据,测试。
http://download.csdn.net/download/sasksinger/10223146

你可能感兴趣的:(MSSQLServer)