0

我正在尝试使用 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 年的表格,如果当年的当前月份大于 8,则为 2012 年

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

4

1 回答 1

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
于 2013-10-25T08:23:54.897 回答