选择特定年份Oracle的记录

Err*_*ion 7 sql oracle11g

我有一个存储事务和日期列的oracle表.如果我需要选择一年的记录说2013年我喜欢这样:

select * 
  from sales_table
 where tran_date >= '01-JAN-2013'
   and tran_date <= '31-DEC-2013'
Run Code Online (Sandbox Code Playgroud)

但我需要一种直接的方式来选择一年的记录,比如从应用程序传递参数'2013',以便在一年内从记录中获得结果而不给出范围.这可能吗?

Kev*_*sox 27

使用提取功能从日期中提取年份:

select * from sales_table
where extract(YEAR from tran_date) = 2013
Run Code Online (Sandbox Code Playgroud)


Dmi*_*nko 8

您可以使用to_date函数

http://psoug.org/reference/date_func.html

select *
  from sales_table
 where tran_date >= to_date('1.1.' || 2013, 'DD.MM.YYYY') and 
       tran_date < to_date('1.1.' || (2013 + 1), 'DD.MM.YYYY')
Run Code Online (Sandbox Code Playgroud)

具有显式比较的解决方案(tran_date> = ...和tran_date <...)能够在tran_date字段上使用索引.

考虑边界:例如,如果tran_date = '31 .12.2013 18:24:45.155'而不是您的代码"tran_date <='31-DEC-2013'"将会错过它