How to convert a string to a date in SQL?

In SQL, you can convert a string to a date using either the CAST function or the CONVERT function.

The syntax for converting a string to a date using the CAST function is:

SELECT CAST('字符串' AS DATE) AS 别名;

For example:

SELECT CAST('2022-01-01' AS DATE) AS date;

The syntax for converting a string to a date using the CONVERT function is:

SELECT CONVERT(DATE, '字符串') AS 别名;

For example,

SELECT CONVERT(DATE, '2022-01-01') AS date;

Among them, ‘string’ is the string to be converted, DATE is the date data type, and alias is the alias of the result.

It is important to note that the converted string must adhere to the date format, otherwise an error will be thrown. The date format is typically in the form of yyyy-mm-dd or yyyy-mm-dd hh:mm:ss.

Leave a Reply 0

Your email address will not be published. Required fields are marked *


广告
Closing in 10 seconds
bannerAds