1. CURRENT_DATE() / CURDATE():
返回当前日期。
SELECT CURRENT_DATE() AS current_date;
2. CURRENT_TIME() / CURTIME():
返回当前时间。
SELECT CURRENT_TIME() AS current_time;
3. CURRENT_TIMESTAMP() / NOW():
返回当前日期和时间。
SELECT CURRENT_TIMESTAMP() AS current_timestamp;
4. DATEPART() / EXTRACT():
从日期中提取特定的部分,如年、月、日。
-- SQL Server
SELECT DATEPART(YEAR, order_date) AS order_year FROM orders;
-- MySQL
SELECT EXTRACT(YEAR FROM order_date) AS order_year FROM orders;
5. DATEADD() / DATE_SUB():
在日期上进行加法或减法操作。
-- SQL Server
SELECT DATEADD(DAY, 7, order_date) AS new_order_date FROM orders;
-- MySQL
SELECT DATE_ADD(order_date, INTERVAL 7 DAY) AS new_order_date FROM orders;
6. DATEDIFF() / TIMESTAMPDIFF():
计算两个日期之间的差距。
-- SQL Server
SELECT DATEDIFF(DAY, order_date, shipped_date) AS days_to_ship FROM orders;
-- MySQL
SELECT TIMESTAMPDIFF(DAY, order_date, shipped_date) AS days_to_ship FROM orders;
7. FORMAT() / DATE_FORMAT():
将日期格式化为特定的字符串。
-- SQL Server
SELECT FORMAT(order_date, 'MM/dd/yyyy') AS formatted_date FROM orders;
-- MySQL
SELECT DATE_FORMAT(order_date, '%m/%d/%Y') AS formatted_date FROM orders;
8. MONTH() / DAY() / YEAR():
获取日期的月、日、年部分。
SELECT MONTH(order_date) AS order_month, DAY(order_date) AS order_day, YEAR(order_date) AS order_year FROM orders;
这只是 SQL 中一些日期和时间函数的示例。确切的函数和语法可能因数据库管理系统而异,因此请根据你使用的数据库系统的文档查找适当的函数。
转载请注明出处:http://www.zyzy.cn/article/detail/3371/SQL