【问题标题】:Selecting multiple database tables from between datetime从日期时间之间选择多个数据库表
【发布时间】:2016-02-18 01:47:23
【问题描述】:

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

  • 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

很抱歉我搞砸了代码和解释,感谢那些可以帮助我解决问题的人。

【问题讨论】:

    标签: sql sql-server-2008


    【解决方案1】:

    您必须从多个表中选择行,将其合并并显示在您的应用程序中。我使用硬编码的日期来生成 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
    

    【讨论】:

      猜你喜欢
      • 2021-12-14
      • 1970-01-01
      • 1970-01-01
      • 2012-01-17
      • 2015-07-10
      • 2013-03-27
      • 1970-01-01
      • 2012-10-31
      相关资源
      最近更新 更多