MSSQLServer資料庫大量資料按月份分表、儲存過程指定時間段跨表分頁查詢
阿新 • • 發佈:2019-01-10
比較完善的大量資料分表功能程式碼,包含建立資料庫、生成資料、測試結果。適合初學分表者使用。 資料按照每個月建立一個數據表,通過儲存過程輸入引數,按照指定日期跨表查詢資料,並且可以分頁查詢。
有如下表:
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) <
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 @[email protected]+' union all select * from '[email protected] +' where '[email protected]+'>='''
+convert(varchar(20), @FromTime,120) + ''' and '
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