Using OPENQUERY with an Oracle database to query a date range

橙三吉。 提交于 2019-12-04 04:54:06

问题


We have an Oracle database that we access through OpenQuery for some stuff. You apparently can't do date comparisons directly in OpenQuery using the OleDB driver, so to get around this you have to convert the dates to Julien dates and compare those numbers. I have the following query that we're trying to execute this in MS SQL Server (GPROD is a Linked Server via the OleDb driver):

SELECT *
FROM  OPENQUERY(GPROD, '
     SELECT * 
     FROM ORD_HDR_HST 
     WHERE (cast(to_number(to_char(SHIP_DATE ,''J'')) as numeric(10,0))  >= cast(to_number(to_char(to_date(''01-JAN-2015'') ,''J'')) as numeric(10,0))  AND 
            cast(to_number(to_char(SHIP_DATE ,''J'')) as numeric(10,0))  <= cast(to_number(to_char(to_date(''21-SEP-2015'') ,''J'')) as numeric(10,0)) )')

This query returns no results but also produces no error.

If I execute this query in Oracle SQL Developer, it works just fine and returns thousands of rows:

SELECT * 
FROM ORD_HDR_HST 
WHERE (cast(to_number(to_char(SHIP_DATE ,'J')) as numeric(10,0))  >= cast(to_number(to_char(to_date('01-JAN-2015') ,'J')) as numeric(10,0))  AND 
       cast(to_number(to_char(SHIP_DATE ,'J')) as numeric(10,0))  <= cast(to_number(to_char(to_date('21-SEP-2015') ,'J')) as numeric(10,0)) )

The SHIP_DATE field is of type DATE and is nullable, if that matters.

Does anyone know what I can do to get this working through OpenQuery?

Edit:

I did a test of the Julien Date conversion and there's definitely something fishy going on, but I don't know what's causing it. If I execute this in Oracle:

select cast(to_number(to_char(to_date('01-JAN-2015') ,'J')) as numeric(10,0)) from dual

I get 2457024

If I execute this on SQL Server:

select * from OPENQUERY(GPROD, 'select cast(to_number(to_char(to_date(''01-JAN-2015'') ,''J'')) as numeric(10,0)) from dual')

I get 1721443


回答1:


I found a solution to the problem. By specifying a mask for the date, it will provide the proper results. Using:

to_char(to_date('01-JAN-2015','DD-MON-YYYY') ,'J') 

instead of

to_char(to_date('01-JAN-2015') ,'J') 

Gives the same result through OpenQuery and directly from Oracle.



来源:https://stackoverflow.com/questions/32699299/using-openquery-with-an-oracle-database-to-query-a-date-range

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!