Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

The following code returns data from 11 tables. Each table contains the year and month. I need to make use of an enddate parameter to check that only tables todate are pulled out. So if the user wants data from 201505 it should pull out all tables only till 201509 as from 201510 tables do not exists assuming we in the month of 201510. Code below:

{

declare 
@enddate varchar(6),
@FirstTableMonth int =201505,
@Table_Name sysname,
@TableMonth int,
@end int,
@CurrentMonth int = 0,
@NextYearMonth int = 1

set @enddate = 201611

WHILE @CurrentMonth < 11
BEGIN

    SELECT  @TableMonth =   CASE WHEN (@FirstTableMonth + @CurrentMonth) % 100 < 13 THEN 
                                @FirstTableMonth + @CurrentMonth 
                            ELSE
                                @FirstTableMonth + 100 - (@FirstTableMonth % 100) + @NextYearMonth
                            END,
                    @NextYearMonth =    CASE WHEN (@FirstTableMonth + @CurrentMonth) % 100 < 13 THEN 
                                    @NextYearMonth
                                ELSE
                                    @NextYearMonth + 1
                                END,
                    @end = case when @enddate 
                    @Table_Name =  'xx_'+CAST(@TableMonth as varchar)+'_T' 

                    SET @CurrentMonth = @CurrentMonth + 1
                    print @Table_Name;
END

}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
147 views
Welcome To Ask or Share your Answers For Others

1 Answer

You get all table names from INFORMATION_SCHEMA.TABLES. So just apply your criteria to get them:

select table_name
from information_schema.tables
where table_type = 'BASE TABLE'
and table_name like 'xx\_______\_T' escape ''  
and table_name >= 'xx_' + CAST(@FirstTableMonth as varchar) + '_T';

SQL fiddle: http://www.sqlfiddle.com/#!6/7b4f5/2


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...