PL SQL using date functions to find partitions

I am trying to teach myself PL SQL and can use a bit of help. I am trying to automate the
dropping of paritions.
Can somebody provide me with an example of how to create some code that will return a liist
of partitions that are older than the N number of years (current year 1/1/2011), or N number of
months, weeks or days...
For example, today is 3/4/2011 How would I create code that will find me partitons that are
older than 2/1/2011 (current first of month -1 month, or ciurrent first of month -N months).
My partition names for all my tables are all in this formate P_YYYY_MM-DD
Please keep in mind this query can retrurn no rows, one row or several rows. If nothing is retrurned
I woiuld liike to print that out for each table.
Thanks in advance to all who answer

This would be a combination of sysdate and either add_months(date,number_of_months) or date-number_of_days, along with a conversion of the date to a pattern that matches your partition name format. Fortunately you've chosen a sensible format that sorts correctly.
So for finding the number of partitions older than so-many years:
select count(*)
from   user_tab_partitions
where table_name = ... and
         partition_name < to_char(add_months(sysdate,-12*5),'"P"_YYYY_MM-DD') Just be careful about whether you want partitions for which the oldest possible date is older than so-many years, or for which the newest possible date is older than so-many years.
Edit: Oh bear in mind that if you select only COUNT(*) then you'll always get a row back even if no matching partitions are found, and COUNT(*) will be 0. If you selected table_name and count(*) then you would get no rows back for tables that have no matching partitions. COUNT(*) never returns null.
Edited by: David_Aldridge on Mar 3, 2011 11:15 PM

Similar Messages

  • How to  use data function using characterstics variable for calculation on

    how to  use data function using characterstics variable for calculation on  attribute as key figure

    Hi Gayatri
    Did you not see my answer for CASE because CASE does indeed offer the use of the BETWEEN clause, but DECODE does not. Let me give you a little synopsis of DECODE.
    In its most simple form it takes 4 values and looks like this: DECODE(A, B, C, D)
    This essentially means, IF A = B THEN C ELSE D
    The trick to solving BETWEEN in a DECODE is to work out algoriths where A = B. Because we don't know how many values are between 00 and 99, although I could guess there were 100 we could of course have 100 parts in the DECODE but that would be awful. How about if we look at it another way and say this:
    IF PART_NUMBER < 'SDK00' THEN pay_amount
    ELSE IF PART_NUMBER > 'SDK99' THEN pay_AMOUNT
    ELSE pay_amount + 100
    This statement only had 2 hard coded values, but how to make DECODE work with less than? Easy, we use the LEAST function. The LEAST function takes 2 values and returns the one with the lowest value. So I use LEAST(PART_NUMBER, 'SDK00') then whenever the PART_NUMBER is lower than SDK00 it will be true. A similar situation exists for the opposite function GREATEST. Putting all of this together then, you can do this:
    DECODE(PART_NUMBER, GREATEST(PART_NUMBER, 'SDK00'), DECODE(PART_NUMBER, LEAST(PART_NUMBER, 'SDK99'), PAY_AMOUNT * 100, PAY_AMOUNT), PAY_AMOUNT)
    In English this can be read as follows:
    IF the PART_NUMBER is greater than or equal to SDK00 and the PART_NUMBER is less than or equal to SDK99 THEN PAY_AMOUNT x 100 ELSE 0
    Best wishes
    Michael

  • How to use date functions in BPEL

    Hi All,
    Is there any wayout for calculating no. of years with a given date and current date in BPEL.
    I am developing a small application where I have to calculate the years of experience of the employees. I am given with the date of joining.I want to subtract the date of joining from the current date. Is there any way-out to calculate no. of years from the given date and current date in BPEL using date functions or something else.
    Please suggest something..
    Thanks in Advance
    Roshni Shankar

    you could use something like this in xsl
    <?xml version="1.0" encoding="UTF-8"?>
    <xsl:stylesheet version="2.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:fo="http://www.w3.org/1999/XSL/Format" xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:fn="http://www.w3.org/2005/xpath-functions">
         <xsl:output method="xml"/>
         <xsl:variable name="date1" select="xs:date('2001-01-01')"/>
         <xsl:variable name="date2" select="xs:date('2010-01-10')"/>
         <xsl:variable name="dif" select="$date2 - $date1"/>
         <xsl:template match="/">
         <all>
              <date1>
                   <xsl:value-of select="$date1"/>
              </date1>
              <date2>
                   <xsl:value-of select="$date2"/>
              </date2>
              <dif-days><xsl:value-of select="fn:days-from-duration($dif)"/></dif-days>
              <dif-years1><xsl:value-of select="fn:years-from-duration($dif)"/></dif-years1> <!-- gives 0 for me -->          
              <dif-years2><xsl:value-of select="fn:days-from-duration($dif) div 356"/></dif-years2>                    
              </all>
         </xsl:template>
    </xsl:stylesheet>

  • When I use the function of "finding keyword", the word would be shown in green. Can I set the colour by myself?

    When I use the function of "finding keyword"(ctrl+f), the keyword would be shown in green. I want to change the highlighted colour to be blue. Is there any function to change the colour?

    See '''''cor-el's''''' answer in this thread: https://support.mozilla.com/en-US/questions/900541
    '''If this reply solves your problem, please click "Solved It" next to this reply when <u>signed-in</u> to the forum.'''
    Not related to your question, but...
    You may need to update some plug-ins. Check your plug-ins and update as necessary:
    *Plug-in check --> http://www.mozilla.org/en-US/plugincheck/
    *Adobe Shockwave for Director Netscape plug-in: [https://support.mozilla.com/en-US/kb/Using%20the%20Shockwave%20plugin%20with%20Firefox#w_installing-shockwave Installing ('''''or Updating''''') the Shockwave plugin with Firefox]
    *Adobe PDF Plug-In For Firefox and Netscape: [https://support.mozilla.com/en-US/kb/Using%20the%20Adobe%20Reader%20plugin%20with%20Firefox#w_installing-and-updating-adobe-reader Installing/Updating Adobe Reader in Firefox]
    *'''''Shockwave Flash''''' (Adobe Flash or Flash): [https://support.mozilla.com/en-US/kb/Managing%20the%20Flash%20plugin#w_updating-flash Updating Flash in Firefox]
    *Next Generation Java Plug-in for Mozilla browsers: [https://support.mozilla.com/en-US/kb/Using%20the%20Java%20plugin%20with%20Firefox#w_installing-or-updating-java Installing or Updating Java in Firefox]

  • SQL using analytical function

    Hi all,
    I want an help in creating my SQL query to extract the data described below:
    I have one table example test containing data like below:
    ID     Desc     Status
    1     T1          DEACTIVE
    2     T2          ACTIVE
    3     T3          SUCCESS
    4     T4          DEACTIVE
    The thing i want to do is selecting all lines with ACTIVE status in this table but is there is no ACTIVE status, my query will give me the last line with DEACTIVE status.
    Can I do this in one query by using analytical function for example, if yes can yiu help me on thaht query.
    regards,
    Raluce

    Hi, Raluce,
    Here's one way to do that:
    WITH got_r_num AS
        SELECT  deptno, ename, job, hiredate
        ,       ROW_NUMBER () OVER ( PARTITION BY  deptno
                                     ORDER BY      job
                                     ,             hiredate  DESC
                                   )  AS r_num
        FROM    scott.emp
        WHERE   job  IN ('ANALYST', 'CLERK')
    SELECT     deptno, ename, job, hiredate
    FROM       got_r_num
    WHERE      job     = 'ANALYST'
    OR         r_num   = 1
    ORDER BY   deptno
    Since I don't have a sample version of your table, I used scott.emp to illustrate.
    Output:
        DEPTNO ENAME      JOB       HIREDATE
            10 MILLER     CLERK     23-JAN-82
            20 SCOTT      ANALYST   19-APR-87
            20 FORD       ANALYST   03-DEC-81
            30 JAMES      CLERK     03-DEC-81
    This query finds all ANALYSTs in each department, regardless of how many there are.  (Deptno 20 happens to have 2 ANALYSTs.)  If there is no ANALYST in a department, then the most recently hired CLERK is included.  (Deptnos 10 and 30 don't have any ANALYSTs.)
    This "partitions", or sub-divides, the table into separate units, one for each department.  In the problem you posted, it looks like you want to operate in the entire table, without sub-dividing it in any way.  To do that, just omit the PARTITION BY clause in the analytic ROW_NUMBER function, like this:
    WITH got_r_num AS
        SELECT  deptno, ename, job, hiredate
        ,       ROW_NUMBER () OVER ( --  PARTITION BY  deptno
                                     ORDER BY      job
                                     ,             hiredate  DESC
                                   )  AS r_num
        FROM    scott.emp
        WHERE   job  IN ('ANALYST', 'CLERK')
    SELECT     deptno, ename, job, hiredate
    FROM       got_r_num
    WHERE      job     = 'ANALYST'
    OR         r_num   = 1
    ORDER BY   deptno

  • Print a DayName without using Date functions

    Hi,
    I have an assignment like without using any date functions i should print a calendar.
    Below is the code without using any datefunctions like dateadd, datediff, datename a calendar has been generated for month and year entered. I want a week name for the dates like sunday ... monday etc. 
    I can take any date from calendar as reference  and calculate based on that date.
    ex: today is 2/20/2014 thursday . Next 7days again will be thursday, same way before 7days will be thursday.
    I need to loop in below procedure and get weekname. 
    Plz help in the code,
    I am using SQL server 2008
    IF OBJECT_ID ('dbo.Calendar1') IS NOT NULL
         DROP PROCEDURE dbo.Calendar1
    GO
    CREATE  PROCEDURE [dbo].Calendar1 --4,1991
       @month int,
       @Year  int
     AS  
     BEGIN
     declare 
     @startdateofMonthYear date,
     @EnddateofMonthYear Date
    Set @startdateofMonthYear=(Select cast(@Year as varchar(4)) +'-'+Right('00'+Cast(@month as varchar(2)),2) +'-'+'01')
    Set @EnddateofMonthYear = (SELECT case when @month IN (1,3,5,7,8,10,12) then cast(@Year as varchar(4)) +'-'+Right('00'+Cast(@month as varchar(2)),2) +'-'+'31'
    when @month IN(4,6,9,11) then cast(@Year as varchar(4)) +'-'+Right('00'+Cast(@month as varchar(2)),2) +'-'+'30'
    else  cast(@Year as varchar(4)) +'-'+Right('00'+Cast(@month as varchar(2)),2) +'-'+(CASE WHEN (@YEAR % 4 = 0 AND @YEAR % 100 <> 0) OR @YEAR % 400 = 0 THEN '29' else '28' End) 
    End) 
    ;WITH CTE_DatesTable
    AS
    Select 1 daysint, Cast(SUBSTRING(cast(@startdateofMonthYear as varchar(20)),1,7) + '-'+CAST(1 as varchar(2)) as DATE) Calendardates
    UNION ALL
    SELECT   daysint+1,Cast(SUBSTRING(cast(@startdateofMonthYear as varchar(20)),1,7) + '-'+CAST(daysint+1 as varchar(2)) as DATE) Calendardates
    FROM CTE_DatesTable
    WHERE  daysint<= 
    (SELECT case when @month IN (1,3,5,7,8,10,12) then 31
    when @month IN(4,6,9,11) then 30
    else  (CASE WHEN (@YEAR % 4 = 0 AND @YEAR % 100 <> 0) OR @YEAR % 400 = 0 THEN 29 else 28 End) 
    End)-1
    Select 
    [DWDateKey]=Calendardates,
    [DayDate]=daysint,
    [MonthNumber]=@Month,
    [MonthName]=Case when @month = 1 then 'January'
     when @month  = 2 then 'February'
     when @month  = 3 then 'March'
     when @month  = 4 then 'April'
     when @month  = 5 then 'May'
     when @month  = 6 then 'June'
     when @month  = 7 then 'July'
     when @month  = 8 then 'August'
     when @month  = 9 then 'September'
     when @month  = 10 then 'October'
     when @month  = 11 then 'November'
     when @month  = 12 then 'December' 
    End,
    [Year]=@Year
    From CTE_DatesTable
    END
    bhavana

    In the above code, where do i pass the year and month?
    (Select 2000 YearID
    Union All
    Select YearID +1 From cte where YearID <2100
     In above condition from 2000 year its displaying.
    If i want in 90's year , Day name will not be correct.
    Deepa

  • How to use  date function in my procedure

    hi Gurus,
    i have a requirement
    where user passes the end_date parametre from front end which get convered to
    End Date => 2012/05/31 00:00:00
    now i based on this end date value i have to calculate the start date which is only month less than the end date, i know i can use add_months function for this requirement but
    my problem is
    l_start_date :=add_months(fnd_date.canonical_to_date(p_end_date),-1);
    (OR)
    l_start_date := add_months(to_date(end_date,'DD-MON-YYYY'),-1);
    all these are returning date format as DD-MON-YYYY eg;
    if user passes from front end 31-may-2012 , in the backend to my procedure it is passing as 2012/05/31 00:00:00
    and my procedure calculating start date and returning as '01-MAY-12',
    but my requiremnt is
    it should return
    Start Date => 2012/05/01 00:00:00
    any pointers on this is highly appreciable,
    thanks in advancee

    HuaMin Chen wrote:
    BluShadow wrote:
    HuaMin Chen wrote:
    Try
    select trunc(to_date('22-AUG-03'), 'MONTH') from dual;?? That is so wrong.
    Is that date 22nd August 2003? 22nd August 1903? 3rd August 2022? 3rd August 1922?
    You have no date format specified in your to_date function.That is fine for 10g or above versions. Thank you.It way work, if you're lucky, but it depends on your sessions NLS settings...
    SQL>  select trunc(to_date('22-AUG-03'), 'MONTH') from dual;
    TRUNC(TO_DATE('22-AU
    01-AUG-0003 00:00:00
    SQL> alter session set nls_date_format = 'YYYY-MM-DD';
    Session altered.
    SQL>  select trunc(to_date('22-AUG-03'), 'MONTH') from dual;
    TRUNC(TO_D
    0022-08-01
    SQL> alter session set nls_date_format = 'HH:MI:SS YYYY-MM-DD';
    Session altered.
    SQL>  select trunc(to_date('22-AUG-03'), 'MONTH') from dual;
    select trunc(to_date('22-AUG-03'), 'MONTH') from dual
    ERROR at line 1:
    ORA-01849: hour must be between 1 and 12
    SQL>So it's certainly not "fine". It's bad practice.
    This must be fine
    select trunc(to_date('22-AUG-03','dd-MON-RR'), 'MONTH') from dual;That's better.

  • Running Total (or) Moving Sum (or) Rollup using Date functions

    I have to pass the Begin date and End date using prompt in my application (for daily basis for one month, monthly and yearly).
    How can i use the date function for Rollup the days values(running total) for the below mentioned SQL
    Table.Date field (@Prompt('Begin_Date','D',,mono,free) and @Prompt('End_Date','D',,mono,free)
    @prompt automatically takes the begin date and end date.
    I need the sql for rollup(running total) on daily basis for one month say jan 1 to jan 31.
    Any idea?

    Check the Oracle on-line documentation on the ROLLUP option of the GROUP BY clause. It should be able to give you running totals.

  • Any Date function to find date on last friday?

    Hi all,
    Is there any date function module to find out the date on last friday....
    And one more thing....any function module to findout the range of dates for the last week...(i.e) date from last week monday to last week friday.
    Thanking u all in advance.
    Regards,
    Chandra Sekhar

    REPORT  ZSN_FRIDAYTEST                          .
    data: days type p.
    data: date type sy-datum.
    parameters: p_date like sy-datum default sy-datum.
    *-- Get the last Friday
    call function 'DAY_IN_WEEK'
      exporting
        datum         = p_date
    IMPORTING
       WOTNR         = days.
    days = days + 2.
    date = p_date - days.
    write:/ '(Assuming Monday is the first day of the week)'.
    write:/ 'Date Entered:', p_date.
    write:/ 'Last Friday:', date.
    *- Range of dates in last week
    data: date1 type sy-datum.
    data: date2 type sy-datum.
    data: days1 type p.
    data: days2 type p.
    call function 'BWSO_DATE_GET_FIRST_WEEKDAY'
      exporting
        date_in        = p_date
    IMPORTING
       DATE_OUT       = date1
    date1 = date1 - 7.
    date2 = date1 + 4.
    write:/ 'Range:', date1, '-', date2.

  • Using Date functions in DP macros

    Hi all,
    I am currently developing a macro in DP...and I need to do an action for the first period of a year.
    I need to identify the first period for this purpose..I m using the date function Bucket_fiscal_period for this purpose but for soem reasons it is not giving a value of 01 for the first period.
    The planning bucket has a weekly bucket pattern.
    I tried to use the layoututvariable_set + layoutvariable and then bucket_fiscal_period to try and see  if the values are getting set.But this seems not to be happening.
    Can anybody tell me whats wrong here?
    Thanks and Regards,
    Anu

    Hello,
    If I am understanding your issue correctly you are trying to identify the weekly bucket in which the first day fo the year falls. To accomplish the same I guess the following should work:
    OPTION 1:
      IF
         WEEK ( DATE ( BUCKET_BDATE ( X ) ) = 1
           THEN
            LAYOUTVARIABLE_SET ( 'FIRSTDAY' )
    ENDIF
    OPTION 2:
    IF
       YEAR_BDATE ( WEEK_BDATE () ) >= WEEK_BDATE ()
        AND
        YEAR_EDATE ( WEEK_BDATE () ) <= WEEK_BDATE ()
             THEN
                LAYOUTVARIABLE_SET ( 'FIRSTDAY' )
    ENDIF
    Hope this helps.
    Regards,
    Abhi

  • Previous quarter from the current date using Date functions

    hi all,
    how can i get the value of the previous quarter and previous month using using NOW() function in the formula.
    regards,
    Rk
    Edited by: Rk on Feb 13, 2009 9:28 AM

    Hi Pk,
    This "DSTR(DADD(NOW(),-1,'Q'),'YYYYQ')" will give you just an year 2008 (if you run this today).
    But this "DSTR(DADD(NOW(),-1,'Q'),'YYYYMM)" will give you an year and month of prev quarter
    200811(if you run this today)
    Ola

  • Trying to use cut function in finder

    I'm new to the mac so this may be a silly question but why can't I cut a file and then paste it somewhere else? I can only copy an item. The edit>cut function is grayed out. Please help!

    This is a data safety measure; a file or folder can easily be lost if it is cut and then the person operating the computer uses the clipboard for something else without pasting it. Drag files from one folder to another to move them.
    (26378)

  • Using LAG function to find a previous record

    Hey,
    I tried searching the forum for this, but I actually didn't even know what to search for, so I'm creating a new thread.
    The SQL below displays a list of prices:
    WITH T AS (
      SELECT 1  AS ID, 'PERM' AS TYPE, 100 AS PRICE, SYSDATE + 1 AS START_DATE FROM DUAL UNION
      SELECT 3  AS ID, 'TEMP' AS TYPE, 90  AS PRICE, SYSDATE + 2 AS START_DATE FROM DUAL UNION
      SELECT 7  AS ID, 'TEMP' AS TYPE, 80  AS PRICE, SYSDATE + 3 AS START_DATE FROM DUAL UNION
      SELECT 8  AS ID, 'PERM' AS TYPE, 75  AS PRICE, SYSDATE + 4 AS START_DATE FROM DUAL UNION
      SELECT 16 AS ID, 'TEMP' AS TYPE, 70  AS PRICE, SYSDATE + 5 AS START_DATE FROM DUAL UNION
      SELECT 20 AS ID, 'TEMP' AS TYPE, 60  AS PRICE, SYSDATE + 6 AS START_DATE FROM DUAL UNION
      SELECT 34 AS ID, 'TEMP' AS TYPE, 50  AS PRICE, SYSDATE + 7 AS START_DATE FROM DUAL
      SELECT T.ID
           , T.TYPE
           , T.PRICE
           , TRUNC (T.START_DATE) AS START_DATE
           , CASE
               WHEN T.TYPE = 'PERM'
                 THEN T.ID
                 ELSE LAG (T.ID, 1, NULL) OVER (PARTITION BY NULL ORDER BY T.ID)
             END AS BASE_ID
        FROM T
    ORDER BY T.START_DATEThe challenge is to produce this output:
    ID TYPE PRICE BASE_ID
    1 PERM   100       1
    3 TEMP    90       1
    7 TEMP    80       1
    8 PERM    75       8
    16 TEMP    70       8
    20 TEMP    60       8
    34 TEMP    50       8What I want to achieve is to bring a column with the ID of the most recent PERM price for TEMP prices,
    and It's own ID for PERM prices.
    My attempt uses LAG to navigate back on the record set, but it uses 1 statically. If there was a way to come up with a number
    for each TEMP price saying how far it was from the most recent PERM, then I could use that number instead of 1.
    Something like:
    ID TYPE PRICE DISTANCE_FROM_PREV_PERM
    1 PERM   100                       0
    3 TEMP    90                       1
    7 TEMP    80                       2
    8 PERM    75                       0
    16 TEMP    70                       1
    20 TEMP    60                       2
    34 TEMP    50                       3Any help will be greatly appreciated.
    Thanks.

    Maybe
    select id,type,price,
           last_value(base_id) ignore nulls over (order by the_row) base_id
    /*     last_value(base_id ignore nulls) over (order by the_row) base_id  -- old way */
      from (select id,type,price,start_date,
                   case type when 'PERM' then id end base_id,
                   row_number() over (order by start_date) the_row
              from t
           )Regards
    Etbin

  • HELP using print function in Finder

    When you right click a selection of Word documents or photos in the finder, I see an option for Print. I thought that if I used this option, the selection would automatically print. Instead, it just opens the application and documents (for example, Microsoft Word) and you still have to select print in the application. What is the difference between this and just opening the files/documents and pressing print?
    Thanks for clearing this up for me.

    The behavior of the Print contextual menu depends on the application.
    Some argue that Word does not handle the Apple Events properly and puts up the dialog instead of just printing the document; others argue Word's behavior is the preferred behavior since the user may want to modify some settings. In the case of Word, there is no difference between this and launching the application and selceting Print.
    Other applications, Preview and TextEdit for example, don't put up the dialog, so there is a difference.
    Hope this helps.

  • Need sql using analytical functions

    Need to formulate this SQL:Please help -
    EMP Table structure is:
    ENAME
    DEPTNO
    SAL
    Here:
    CUMDEPTTOT – Running cumulative Total by Department
    SALBYDEPT – Total salary by Department
    CUMTOT – Running cumulative total
    DEPTNO ENAME SAL CUMDEPTTOT SALBYDEPT CUMTOT
    10 MILLER 1300 1300 8750 1300
    10 CLARK 2450 3750 8750 3750
    10 KING 5000 8750 8750 8750
    Thanks

    ravikumar.sv wrote:
    This has been asked today....
    I think you both are friends....
    Re: Please provide SQL
    follow up that thread...As I suspected, it's a homework question. {noformat}*sigh*{noformat}. Let's hope their tutor checks the internet for them asking the question and fails them.

Maybe you are looking for