convert decimal to date during where clause [duplicate]

大憨熊 提交于 2020-01-15 11:52:12

问题


Possible Duplicate:
Convert DB2 SQL Decimal to DATE

I have a db2 database and I want to convert a decimal to a date during the where clause in a select statement.

The decimal date could be 12 or 13 characters long depending on the month.

12 characters:

1,241,999.00 should become: 1999/1/24

13 Characters:

12,241,999.00 should become: 1999/12/24

The column name is DECIMALCOLUMN:

Select * from table1 WHERE
cast(replace(convert,DECIMALCOLUMN,date)) = @date

回答1:


I see: You want some way of rearranging the digits of a number to become a date. It looks like the encoding is [m]mddyyyy. (Why isn't that a date datatype in the database?)

The number needs to be converted to a string and then substrings arranged and converted to a date. Given the complexities here, a conversion function should be written in lieu of the field being altered to be a proper datatype. Something like this should do it (untested, no access to db2):

create function decimaldate(decdate DECIMAL) 
returns DATE
return
with tmp (dstr) as
(
    select substr(digits (decdate),8)
    from sysibm.sysdummy1
)
select
  date (substr(dstr,4,4) || '-' ||
        substr(dstr,1,2) || '-' ||
        substr(dstr,3,2)
       )
from tmp

This converts the number to a string, reformats the string as yyyy-mm-dd and converts to a date. (I used this as a basis.)

So the solution to the original question is simply to write:

SELECT * 
FROM table1
WHERE decimaldate(DECIMALCOLUMN) = @date

With such a screwy way of encoding the date in the database, having the function always available should prove invaluable.



来源:https://stackoverflow.com/questions/8606476/convert-decimal-to-date-during-where-clause

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