从datetime之间选择多个数据库表

时间:2016-02-18 01:47:23

标签: sql sql-server-2008

我想在我网站上的datepicker中选择的日期范围之间选择一个数据库表,我的示例数据库表名是:

  • output_11FEB2016
  • output_13FEB2016
  • output_15FEB2016
  • output_21FEB2016

我想选择要在我的网站上显示和显示其内容的表格,这是我目前的代码,来自我对我的研究的理解。

ALTER PROCEDURE [dbo].[gen048_mLIST] 
-- Add the parameters for the stored procedure here


@gfromDate varchar(10),
@gtoDate varchar(10)


AS

SET NOCOUNT ON

declare @sql varchar(5000)

set @sql='select * output_'


if(@gfromDate<>'' and @gtoDate<>'')
begin
    set @sql=@sql+'between '+convert(datetime,'''+@gfromDate+''')+' and '+convert(datetime,'''+@gtoDate+''')+' '


--print @sql
exec(@sql)

-- [dbo].[gen048_mLIST] '2-16-2016','2-18-2016'

END

对不起我的乱码和解释,我很感谢那些可以帮我解决问题的人。

1 个答案:

答案 0 :(得分:2)

您必须从多个表中选择行,UNION并在应用程序中显示它。我使用硬编码日期生成SQL,但您可以修改/扩展它以满足您的要求。

declare @gfromDate varchar(10) = '11/02/2016'
declare @gtoDate varchar(10) = '24/02/2016'
declare @fromDate datetime
declare @toDate datetime
declare @totaldays int

set @fromDate  = (select convert (date, @gfromDate, 104))
set @toDate  = (select convert (date, @gtoDate, 104))

-- get total number of days between from and to dates
set @totaldays = (select datediff(day,@fromdate,@toDate))

declare @sql varchar(max) = ''
declare @tablename varchar(20)
declare @counter int = 1

-- generate the sql to get data from the tables within a date range
while @counter < @totaldays
begin
    set @tablename = (select convert(varchar(11), @fromDate, 106))
    set @tablename = replace(@tablename,' ','')

    -- check if table exists
    --if object_id(@tablename, 'U') is not null
    --begin
    set @sql = @sql + 'select * from output_' +  @tablename 
    if(@counter < @totaldays-1)
    begin
        set @sql = @sql + ' union '
    end
    set @fromDate = dateadd(day,1,@fromDate)
    set @counter = @counter + 1
    --end
end
print @sql

SQL生成

select * from output_11Feb2016 union 
select * from output_12Feb2016 union 
select * from output_13Feb2016 union 
select * from output_14Feb2016 union 
select * from output_15Feb2016 union 
select * from output_16Feb2016 union 
select * from output_17Feb2016 union 
select * from output_18Feb2016 union 
select * from output_19Feb2016 union 
select * from output_20Feb2016 union 
select * from output_21Feb2016 union 
select * from output_22Feb2016