【问题标题】:Get table names if month is greater than 8th of current year?如果月份大于当年的 8 号,则获取表名?
【发布时间】:2013-10-25 07:37:56
【问题描述】:

我正在尝试使用 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 年

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

【问题讨论】:

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


    【解决方案1】:

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

        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
    

    【讨论】:

      猜你喜欢
      • 2020-03-25
      • 2016-09-28
      • 1970-01-01
      • 2023-02-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多