📅  最后修改于: 2023-12-03 15:20:14.260000             🧑  作者: Mango
When working with SQL, it is often necessary to convert datetime values to date values for easier manipulation or comparison. In SQL, you can use various built-in functions and operators to extract the date portion of a datetime value.
The CONVERT
function is used to convert a datetime value to a date value. The syntax is:
CONVERT(date, datetime_expression)
where date
is the target data type and datetime_expression
is the datetime value to be converted.
For example, to convert the current datetime to a date value, you can use:
SELECT CONVERT(date, GETDATE())
This will return the current date in the format YYYY-MM-DD.
The CAST
operator can also be used to convert a datetime value to a date value. The syntax is:
CAST(datetime_expression AS date)
For example, to convert a datetime column order_date
to a date column, you can use:
SELECT CAST(order_date AS date) AS order_date
FROM orders
This will return the order_date
column with only the date portion.
The DATEADD
function can be used to subtract the time portion from a datetime value. The syntax is:
DATEADD(datepart, number, date)
where datepart
is the unit to be added or subtracted (e.g. day, month, year), number
is the number to be added or subtracted, and date
is the datetime value.
For example, to extract only the date portion of the order_date
column and remove the time portion, you can use:
SELECT DATEADD(day, DATEDIFF(day, 0, order_date), 0) AS order_date
FROM orders
This will return the order_date
column with only the date portion in the format YYYY-MM-DD.
Converting datetime values to date values is a common task in SQL, and can be accomplished using various built-in functions and operators. Whether you use CONVERT
, CAST
, or DATEADD
, pay attention to the syntax and target data type to get the desired result.