While working with raw data, you may frequently face date values stored as text. Converting these values to a date data type is very important since dates may be more valuable during analysis. In SQL Server, converting a string to date can be achieved in different approaches.
处理原始数据时,您可能经常会遇到存储为文本的日期值。 将这些值转换为日期数据类型非常重要,因为在分析过程中日期可能更有价值。 在SQL Server中,可以通过不同的方法将字符串转换为日期。
In general, there are two types of data type conversions:
通常,有两种类型的数据类型转换:
In this article, we will explain how a string to date conversion can be achieved implicitly, or explicitly in SQL Server using built-in functions such as CAST(), TRY_CAST(), CONVERT(), TRY_CONVERT() and TRY_PARSE().
在本文中,我们将说明如何使用内置函数(例如CAST(),TRY_CAST(),CONVERT(),TRY_CONVERT()和TRY_PARSE())在SQL Server中隐式或显式地实现字符串到日期的转换。
As mentioned above, converting a data type implicitly is not visible to the user, as an example when you are comparing two fields or values having different data types:
如上所述,例如,当您比较两个具有不同数据类型的字段或值时,隐式转换数据类型对用户不可见:
SELECT * FROM information_schema.columns where '1' = 1
In SQL Server, converting string to date implicitly depends on the string date format and the default language settings (regional settings); If the date stored within a string is in ISO formats: yyyyMMdd or yyyy-MM-ddTHH:mm:ss(.mmm), it can be converted regardless of the regional settings, else the date must have a supported format or it will throw an exception, as an example while working under the regional settings “EN-US”, if we try to convert a string with dd/MM/yyyy format it will fail since it tries to convert it as MM/dd/yyyy format which is supported.
在SQL Server中,将字符串转换为日期隐式取决于字符串日期格式和默认语言设置(区域设置);默认值为0。 如果字符串中存储的日期采用ISO格式: yyyyMMdd或yyyy-MM-ddTHH:mm:ss(.mmm),则无论区域设置如何均可进行转换,否则该日期必须具有受支持的格式,否则它将抛出一个例外,例如在区域设置“ EN-US”下工作时,如果我们尝试将字符串转换为dd / MM / yyyy格式,则它将失败,因为它将尝试将其转换为MM / dd / yyyy格式。支持的。
SELECT * FROM information_schema.columns where GETDATE() > '13/12/2019'
Will throw the following exception:
将抛出以下异常:
Msg 242, Level 16, State 3, Line 1 The conversion of a varchar data type to a datetime data type resulted in an out-of-range value.
消息242,级别16,状态3,第1行 从varchar数据类型到datetime数据类型的转换导致值超出范围。
Screenshot:
屏幕截图:
But, if we switch the day and month parts, it will succeed:
但是,如果我们切换日期和月份部分,它将成功:
SELECT * FROM information_schema.columns where GETDATE() > '13/12/2019'
Screenshot:
屏幕截图:
You can check out this official documentation here to learn more about how to change SQL Server language settings.
您可以在此处查看此官方文档,以了解有关如何更改SQL Server语言设置的更多信息。
Additionally, you can read more about implicitly converting date types in SQL Server, by referring to this article: Implicit conversion in SQL Server.
此外,通过参考本文,您可以了解有关SQL Server中隐式转换日期类型的更多信息: SQL Server中的隐式转换 。
The second approach for converting data types is the explicit conversion which is done by using some functions or tools. In SQL Server, converting a string to date explicitly can be achieved using CONVERT(). CAST() and PARSE() functions.
转换数据类型的第二种方法是显式转换,这是通过使用某些功能或工具来完成的。 在SQL Server中,可以使用CONVERT()将字符串显式转换为日期。 CAST()和PARSE()函数。
CAST() is the most basic conversion function provided by SQL Server. This function tries to convert given value to a specified data type (data type length can only be specified).
CAST()是SQL Server提供的最基本的转换函数。 此函数尝试将给定值转换为指定的数据类型(只能指定数据类型的长度)。
Example:
范例 :
SELECT CAST('12/01/2019' as date) as StringToDate , CAST(GETDATE() as VARCHAR(50)) as DateToString
Result:
结果 :
Note that in SQL Server, converting a string to date using CAST() function depends on the language settings similar to implicit conversion, as we mentioned in the previous section, so you can only convert ISO formats or supported formats by the current language settings.
请注意,在SQL Server中,使用CAST()函数将字符串转换为日期取决于类似于隐式转换的语言设置,正如我们在上一节中提到的那样,因此您只能通过当前语言设置转换ISO格式或支持的格式。
CONVERT() function is more advanced than CAST() since the conversion style can be specified. This function takes 3 arguments: (1) the desired data type, (2) the input value and (3) the style number (optional).
由于可以指定转换样式,因此CONVERT()函数比CAST()更高级。 此函数使用3个参数:(1)所需的数据类型,(2)输入值,以及(3)样式号(可选)。
If the style number is not passed to the function, it acts like the CAST() function. But, if the style argument is passed, it will try to convert the value based on that style. As an example, if we try to convert “13/12/2019” value to date without specifying the style number, it will fail since it is not supported by the current language setting:
如果样式号未传递给该函数,则其行为类似于CAST()函数。 但是,如果传递了样式参数,它将尝试根据该样式转换值。 例如,如果我们尝试将“ 13/12/2019”值转换为日期而不指定样式号,则它将失败,因为当前语言设置不支持该值:
SELECT CONVERT(DATETIME,'13/12/2019')
Result:
结果:
But, if we pass 103 as style number (103 is corresponding of dd/MM/yyyy date format), it will succeed:
但是,如果我们通过103作为样式编号(103对应于dd / MM / yyyy日期格式),它将成功:
SELECT CONVERT(DATETIME,'13/12/2019',103)
Result:
结果:
For more information about CONVERT() function and date style numbers, you can refer to the following articles:
有关CONVERT()函数和日期样式编号的更多信息,可以参考以下文章:
PARSE() is SQL CLR function that use .Net framework Parse() function. PARSE() syntax is as follows:
PARSE()是使用.Net框架Parse()函数SQL CLR函数。 PARSE()语法如下:
PARSE(<value> AS <data type> [USING <culture>])
PARSE(<值> AS <数据类型> [使用<文化>])
If the culture info is not specified, PARSE() acts similar to CAST() function, but when the culture is passed within the expression, the function tries to convert the value to the desired data type using this culture. As an example, if we try to parse 13/12/2019
value without passing the culture information, it will fail since “dd/MM/yyyy” is not supported by the default language settings.
如果未指定区域性信息,则PARSE()的行为类似于CAST()函数,但是当在表达式中传递区域性时,函数会尝试使用此区域性将值转换为所需的数据类型。 例如,如果我们尝试在不传递区域性信息的情况下解析13/12/2019
值,则它将失败,因为默认语言设置不支持“ dd / MM / yyyy”。
But, if we pass “AR-LB” as culture (Arabic – Lebanon), where “dd/MM/yyyy” is supported, the conversion succeeds:
但是,如果我们将“ AR-LB”作为一种文化(阿拉伯语-黎巴嫩)通过,其中支持“ dd / MM / yyyy”,则转换成功:
One of the main issues of the data type conversion functions is that they cannot handle the erroneous value. As an example, many times you may face bad date values such as “01/01/0000”; these values cannot be converted and will throw a data conversion exception.
数据类型转换函数的主要问题之一是它们不能处理错误的值。 例如,很多时候您可能会遇到错误的日期值,例如“ 01/01/0000”; 这些值无法转换,将引发数据转换异常。
To solve this issue, you can use TRY_CAST(), TRY_CONVERT() or TRY_PARSE() functions to check if the value can be converted or not, if so, the function will return the conversion result, else it will return a NULL value.
要解决此问题,可以使用TRY_CAST(),TRY_CONVERT()或TRY_PARSE()函数检查该值是否可以转换,如果可以,则该函数将返回转换结果,否则将返回NULL值。
Example:
例:
SELECT TRY_CAST('01/01/2000' as date), TRY_CAST('01/01/0000' as date)
Result:
结果:
To understand the differences among these conversion functions and also to decide which function to use in which scenario, you can refer to this site.
要了解这些转换功能之间的差异,并确定在哪种情况下要使用哪个功能,请访问此站点 。
In this article, we explained data conversion approaches in general. Then we showed how, while using SQL Server, converting a string to date can be achieved using these approaches. We explained the system functions provided by SQL Server by giving some examples and external links that provide more details.
在本文中,我们总体上介绍了数据转换方法。 然后,我们展示了在使用SQL Server时如何使用这些方法将字符串转换为日期。 通过提供一些示例和提供更多详细信息的外部链接,我们解释了SQL Server提供的系统功能。
翻译自: https://www.sqlshack.com/sql-server-functions-for-converting-string-to-date/
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。
发布者:全栈程序员栈长,转载请注明出处:https://javaforall.cn/184444.html原文链接:https://javaforall.cn