date as parameter in sql query and today

3 ビュー (過去 30 日間)
Derik
Derik 2012 年 3 月 30 日
回答済み: Piyush Kumar 2024 年 11 月 26 日 10:13
Hello, I'm trying to use the date as parameter in a sql query in matlab I tried several possibilities but must be missing something in formatting... The date format in sql table is yyyy-mm-dd. It would be something like: result=extract(inputdate) conn = database('DB','',''); string = 'select * from Database where P_Date<inputdate' etc
As an alternative, I would like to do the same with something like today() in excel, e.g. result=extract(inputdate) conn = database('DB','',''); string = 'select * from Database where P_Date<today' etc Thank you very much in advance D.

回答 (1 件)

Piyush Kumar
Piyush Kumar 2024 年 11 月 26 日 10:13
Hi,
To use a date as a parameter in an SQL query in MATLAB, you need to ensure the date is formatted correctly and passed into the query string properly.
1. Using a specific date:
inputdate = '2024-11-26';
query = sprintf('SELECT * FROM Database WHERE P_Date < ''%s''', inputdate);
disp(query);
conn = database('DB', '', '');
result = fetch(conn, query);
2. Using today’s date:
% Get today's date in 'yyyy-mm-dd' format
todayDate = datestr(now, 'yyyy-mm-dd');
query = sprintf('SELECT * FROM Database WHERE P_Date < ''%s''', todayDate);
disp(query);
conn = database('DB', '', '');
result = fetch(conn, query);
In the first example, inputdate is a specific date you want to use in the query. In the second example, todayDate is dynamically generated to represent the current date.
Make sure your date format matches the format used in your SQL table. The datestr function is used to format the current date correctly.
In MySQL workbench, I replicated the scenario using following SQL queries -
CREATE TABLE data (
id INTEGER PRIMARY KEY AUTO_INCREMENT,
P_Date DATE
);
INSERT INTO data (P_Date) VALUES ('2024-11-25');
INSERT INTO data (P_Date) VALUES ('2024-11-26');
INSERT INTO data (P_Date) VALUES ('2024-11-27');
SELECT * FROM data WHERE P_Date < '2024-11-26';
SELECT * FROM data WHERE P_Date < CURRENT_DATE;

カテゴリ

Help Center および File ExchangeDatabase Toolbox についてさらに検索

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by