User`s guide
6 Using Database Toolbox Functions
6-8
Create a Query Using a Date
This example shows how to format a date in an SQL query.
When you want to write an SQL statement that selects data from your database using a
date, you need to format the date according to your database specifications. Consult your
database documentation for the right formatting. This example shows date formatting for
an Oracle database.
Connect to the Database
Connect to Oracle using native ODBC. For example, the following code assumes you are
connecting to a data source named Oracle with user name username and password
pwd.
conn = database.ODBCConnection('Oracle','username','pwd');
Create and Execute a Query Using a Date
Create an SQL statement sqlquery that contains the full query. Execute the query
using the exec function. The following code uses the table test_types and the column
test_dt. The WHERE clause contains Oracle SQL code for filtering the records based
on the date. The test_dt column data type is an Oracle date type. Filter records for
the dates after June 9, 2013 using the test_dt column by entering this date in the
Oracle function to_date to convert your date string to an Oracle date type. For a string
'2013-06-09', specify the format as 'YYYY-MM-DD'. This is one way to format a date
in Oracle. Consult your Oracle documentation for alternatives.
sqlquery = ['select * from test_types '...
'where test_dt > to_date(''2013-06-09'',''YYYY-MM-DD'')'];
curs = exec(conn,sqlquery);
Display the selected data using the fetch function.
curs = fetch(curs);
curs.Data
ans =
'2013-06-10 15:11:00' '2013-06-10 15:11:22.500000'
'2013-06-10 15:13:00' '2013-06-10 15:13:21.870003'
'2013-06-10 15:16:00' '2013-06-10 15:16:45.099998'
...