I need to generate a list of values in an Oracle DB with the following columns of data:

ITEM_TYPE             VARCHAR2(20)
ITEM_LAST_UPDATED     DATE
ITEM_UPDATE_TOLERANCE NUMBER(1)

The only data that should be send out to the console would be items that have the date in 'ITEM_LAST_UPDATED' less than the sysdate minus the integer value within 'ITEM_UPDATE_TOLERANCE'.

So, if I wanted to just show the ones that were one hour past due, I can do:

select ITEM_TYPE from MY_TABLE
where
to_char(ITEM_LAST_UPDATED, 'DD-MON-YYYY HH24:MI')
<=
to_char(sysdate - interval '1' hour, 'DD-MON-YYYY HH24:MI');

However, rather than using the '1' in the above statement, I need to replace it with the numeric value of ITEM_UPDATE_TOLERANCE.

I tried several different versions, but all error (such as):

select ITEM_TYPE from MY_TABLE
where
to_char(ITEM_LAST_UPDATED, 'DD-MON-YYYY HH24:MI')
<=
to_char(sysdate - interval to_number(ITEM_UPDATE_TOLERANCE) hour, 'DD-MON-YYYY HH24:MI');
有帮助吗?

解决方案

Why are you converting a perfect DATE column to a character value just to compare it another DATE value converted to a character column.

Simply use:

ITEM_LAST_UPDATED <= sysdate - interval '1' hour

To achieve what you want, just multiply the value:

ITEM_LAST_UPDATED <= sysdate - (interval '1' hour) * ITEM_UPDATE_TOLERANCE

There is also absolutely no need to convert a number to a number using the to_number() function.

其他提示

As an alternative to @a_horse_with_no_name's interval multiplication trick, or San's division method, you can also use the numtodsinterval() function:

ITEM_LAST_UPDATED <= sysdate - numtodsinterval(ITEM_UPDATE_TOLERANCE, 'HOUR')

As an example:

select sysdate, sysdate - numtodsinterval(3, 'HOUR') from dual;

SYSDATE             SYSDATE-NUMTODSINTE
------------------- -------------------
2014-03-07 19:08:27 2014-03-07 16:08:27

Well you can try using simple calculation

select ITEM_TYPE from MY_TABLE
where
ITEM_LAST_UPDATED
<=
sysdate - (ITEM_UPDATE_TOLERANCE/24);

Calculation of ITEM_UPDATE_TOLERANCE/24 will convert hours into days and then can be subtracted from sysdate.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top