简体   繁体   English

从varchar转换为SQL Server中的日期

[英]Convert from varchar into date in SQL Server

This looks easy solution but I can't seem to figure out as to why this is not working for me. 这看起来很容易解决,但我似乎无法弄清楚为什么这对我不起作用。 I have a column that has data like this: 我有一个列有这样的数据:

DateField
----------
12/16/2016
11/06/2016

All I want to do is to convert from varchar into a date column, but I am getting this error: 我想要做的就是从varchar转换为date列,但我收到此错误:

Conversion failed when converting date and/or time from character string. 从字符串转换日期和/或时间时转换失败。

Here is my simple query: 这是我的简单查询:

select convert (date, DateField) as convertedField 
from myTable

Nothing wrong with the two examples you have given. 你给出的两个例子没有错。 There are some bad dates in your table which cannot be converted to date. 您的表中有一些不良日期无法转换为日期。

Use TRY_CONVERT function for bad dates it will return NULL 对于错误的日期使用TRY_CONVERT函数它将返回NULL

select TRY_Convert(date,DateField)
From myTable

You should always store dates in DATE/DATETIME datatype. 您应始终以DATE/DATETIME数据类型存储日期。

If you want to see the records which cannot be converted to date then 如果要查看无法转换为日期的记录

select DateField
From myTable
Where TRY_Convert(date,DateField) IS NULL

If working with a specific date format like mm/dd/yyyy You can specify it in Convert() function like the following 如果使用特定日期格式(如mm/dd/yyyy您可以在Convert()函数中指定它,如下所示

CONVERT(DATETIME,DATAFIELD,101)

If it still is not working, use TRY_CONVERT() to get which rows are throwing this exception: 如果它仍然无法正常工作,请使用TRY_CONVERT()来获取抛出此异常的行:

SELECT * 
FROM TBL 
WHERE TRY_CONVERT(DATETIME, DATAFIELD, 101) IS NULL

This will return rows that cannot be converted 这将返回无法转换的行

TRY_CONVERT() will return NULL if conversion failed 如果转换失败, TRY_CONVERT()将返回NULL

Read more about DateTime formats here: SQL Server CONVERT() Function tutorial 在此处阅读有关DateTime格式的更多信息: SQL Server CONVERT()函数教程

Read TRY_CONVERT MSDN Article 阅读TRY_CONVERT MSDN文章

You need to specify the format of date time while formatting. 您需要在格式化时指定日期时间的格式。 The date in your table is currently in US format so you should pass the third argument 101 in your convert function. 表格中的日期目前采用美国格式,因此您应该在转换函数中传递第三个参数101。

SELECT CONVERT(date,[DateField],101) FROM myTable;

Working Fiddle here http://rextester.com/NYKR49788 在这里工作小提琴http://rextester.com/NYKR49788

More info about date time style here: https://msdn.microsoft.com/en-us/library/ms187928.aspx 有关日期时间样式的更多信息,请访问: https//msdn.microsoft.com/en-us/library/ms187928.aspx

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM