Apache Derby 没有本机函数,但可以创建自己的函数并从数据库中调用它。
首先,创建将转换日期的java方法:
package DbExamples.StoredProcedures;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
public class DateUtilities {
public static String convertDate(String inputDateString, String currentFormat, String outputFormatString) throws ParseException {
SimpleDateFormat inputFormat = new SimpleDateFormat(currentFormat);
Date inputDate = inputFormat.parse(inputDateString);
SimpleDateFormat outputFormat = new SimpleDateFormat(outputFormatString);
String result = outputFormat.format(inputDate);
return result;
}
}
然后通过在数据库上运行以下sql语句将jar文件注入数据库:
CALL SQLJ.REMOVE_JAR('App.StoredProcedures', 0);
CALL SQLJ.INSTALL_JAR('C:\dev\DbExamples\dist\DbExamples.jar', 'App.StoredProcedures', 0);
CALL SYSCS_UTIL.SYSCS_SET_DATABASE_PROPERTY('derby.database.classpath', 'App.StoredProcedures');
现在通过运行以下 sql 语句在数据库中创建存储过程:
drop function convertDate;
create function convertDate(dateString varchar(8000), currentFormat varchar(8000), outputFormat varchar(8000))
returns varchar(8000)
parameter style java no sql
language java external name 'DbExamples.StoredProcedures.DateUtilities.convertDate';
现在您可以运行查询了:
select
convertDate('3 Jun 2016', 'd MMM yyyy', 'yyyy-MM-dd HH:mm:ss.SSS') as dt
from SYSIBM.SYSDUMMY1;
返回:
2016-06-03 00:00:00.000
事实上,该技术甚至可以用于将 varchar 转换为 TIMESTAMP:
select
cast(convertDate('3 Jun 2016', 'd MMM yyyy', 'yyyy-MM-dd HH:mm:ss.SSS') as timestamp) as dt
from SYSIBM.SYSDUMMY1;