如果月份大于当前年份的第8个,请获取表格名称?

时间:2013-10-25 07:37:57

标签: sql sql-server database sql-server-2008

我正在尝试使用SSIS获取用于存档的表格,因为我正在编写查询,所以在查询中我逐年循环,以获得那些年创建的表格列表,这是我想要做的,

1) Get the tables created in year which is equal to looping year variable ?
2) If the current year month is greater than 8 then select then select the tables for the last year otherwise select till year before 

我试过,

 SELECT name,month(create_date),YEAR(create_date)  
 FROM sys.Tables where  (name like 'F%' OR name like 'G%') 
  and 
   ((month(getdate())>8 and datediff(YEAR,create_date,GETDATE()) = loopVariableDifferance)
      or (datediff(YEAR,create_date,GETDATE())= loopVariableDifferance-1) )
 order by name

 //loopVariableDifferance is start with 5 for 2008 ,4 for 2009,3 for 2010 continues till 0 for 2013 

我想要的就是在2008年的第一个循环,2009年的第二个,2010年的第三个循环,2011年的第四个循环和2012年,如果当前的当前月份大于8

任何帮助都会很棒。提前致谢。

1 个答案:

答案 0 :(得分:0)

试试这个,它会给你表名。

    DECLARE @tables TABLE(id INT IDENTITY(1,1), name VARCHAR(500),YearsAgo INT, YearCreated INT, MonthCreated INT);
    DECLARE @loopmax INT, @Thisyertest INT, @DynamicSQL NVARCHAR(4000);
    SET @Thisyertest = 1;

    IF MONTH(GETDATE()) > 8
        SET @Thisyertest = 0; /*If this is 0 it will include 2012 results*/

    INSERT INTO @tables(name,YearsAgo, YearCreated, MonthCreated)
    SELECT 
    name
    , DATEDIFF(YEAR,create_date,GETDATE()) YearsAgo
    , YEAR(create_date) YearCreated
    , MONTH(create_date) MonthCreated
    FROM sys.Tables 
    ORDER BY YearCreated ASC, MonthCreated ASC, name

    SET @loopmax = 5 /*Years ago*/
    WHILE @loopmax > (0 + @Thisyertest) /*We offset 1 less loop if we need to exclude last year*/
    BEGIN
        PRINT CONVERT(VARCHAR,@loopmax);

        IF EXISTS(SELECT * FROM @tables T1 WHERE T1.YearsAgo = @loopmax)
        BEGIN
            SELECT ABS(5-@loopmax+1) LoopNumber, id,name,YearsAgo, YearCreated, MonthCreated
            FROM @tables T1
            WHERE T1.YearsAgo = @loopmax;
        END
        SET @loopmax = @loopmax - 1;
    END