开发者

How to improve the following SQL select date in RDB

I'm working on a .Net WinForms appliation that is connecting to a legacy RDB database...

Some of the fields for dates are stored as integers (imagine 2010-01-04 was the integer 20100104)

In the .Net world, I'd much rather work with datetime objects and I've been able to convert the integer into a date, just that it looks so ugly, takes up lots of lines, is prone to errors and I'm wondering if anyone would be able to improve it...Thanks heaps!

Note - I cannot edit the database so creating any form of "function" is out of the question...

Here's my current way of selecting the integer as a datetime:

select
CAST(
SUBSTRING(DATE_COL AS VARCHAR(8)) FROM 1 FOR 4) ||
'-' ||
SUBSTRING(CAST(DATE_COL) AS VARCHAR(8)) FROM 5 FOR 2) ||
'-' ||
SUBSTRING(CAST(DATE_COL) AS VARCHAR(8)) FROM 7 FOR 2) ||
' 00:00:00'
AS TIMESTAMP) AS DAT开发者_JS百科E_COL
from MY_TABLE
where ...


It's been a while since I had to mess with Rdb. I seem to recall that there was a way to convert to a TIMESTAMP datatype by doing something like

CAST('YYYYMMDDHHMMSSTT' AS TIMESTAMP)

WHERE 'YYYYMMDDHHNNSSTT' was a character string in year-month-day-hour-min-sec-fraction format. You may need to use DATE ANSI here instead of TIMESTAMP - like I say, it's been a while. Regardless, the following might work:

SELECT CAST((CAST(DATE_COL AS CHAR(8)) || '00000000') AS TIMESTAMP)...

which is still ugly but is perhaps better than all the substringing. Anyways, play with it a bit and I'm sure you'll get it.


In Oracle, you can use the TO_DATE after you've cast the date_col to a string:

TO_DATE(TO_CHAR(date_col), 'YYYYMMDD')

...or 'YYYYDDMM' for the date format.

References:

  • TO_DATE
  • TO_CHAR


Why not use LINQ library? It is very nice and powerful.

What are the typical queries that you are running (high-level pseudocode please).

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜