SQL 如何在sql中将varchar转换为日期时间
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/20134486/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to cast varchar to datetime in sql
提问by JpCrow
I need to cast a string to a datetime so i can compare it later.
我需要将字符串转换为日期时间,以便稍后进行比较。
The varchar that i have is like this format:
我拥有的 varchar 是这样的格式:
29/11/2013 12:00:00 a.m.
And i need it to cast to:
我需要它投射到:
2013-11-29 00:00:00.000
Im using MSSQL Server 2012
我使用的是 MSSQL Server 2012
Thx for all
谢谢大家
采纳答案by Erick
Please, have a look a CAST and CONVERTfor more information.
请查看CAST 和 CONVERT以获取更多信息。
Here are some examples:
这里有些例子:
-- converting from DD-MM-YYYY
select CONVERT(datetime, '29/11/2013 12:00:00 AM', 103)
-- converting from MM-DD-YYYY
select CONVERT(datetime, '11/29/2013 12:00:00 AM', 101)
回答by siva
IF Your date is of type varchar in the database then if you need to retrieve then these cases arises:: case1:if your data is in the format of "dd-MM-yyyy" then you need to use query as follows Query:: select * from [yourTableName] where convert(datetime,YourDateColumn,103) between '2016-02-12'(yyyy-MM-dd) AND '2016-03-12'
如果您的日期在数据库中是 varchar 类型,那么如果您需要检索,则会出现这些情况::case1:如果您的数据采用“dd-MM-yyyy”格式,则您需要使用如下查询查询: select * from [yourTableName] where convert(datetime,YourDateColumn,103) between '2016-02-12'(yyyy-MM-dd) AND '2016-03-12'
case2:if your data is in the format of "dd-MM-yyyy HH:mm:ss"
case2:如果你的数据格式为“dd-MM-yyyy HH:mm:ss”
then you need to use query as follows Query:: select * from [yourTableName] where convert(datetime,YourDateColumn,105) between '2016-02-12'(yyyy-MM-dd) AND '2016-03-12'
那么你需要使用如下查询 Query:: select * from [yourTableName] where convert(datetime,YourDateColumn,105) between '2016-02-12'(yyyy-MM-dd) AND '2016-03-12'