SQL 在sql server中将字符串转换为日期
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13277674/
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
convert string to date in sql server
提问by birdy
How do I convert YYYY-MM-DD
(2012-08-17
) to a date in SQL Server?
如何将YYYY-MM-DD
( 2012-08-17
)转换为 SQL Server 中的日期?
I don't see this format listed on the help page: http://msdn.microsoft.com/en-us/library/ms187928.aspx
我在帮助页面上没有看到这种格式:http: //msdn.microsoft.com/en-us/library/ms187928.aspx
回答by marc_s
I think style no. 111 (Japan) should work:
我认为风格没有。111(日本)应该工作:
SELECT CONVERT(DATETIME, '2012-08-17', 111)
And if that doesn't work for some reason - you could always just strip out the dashes and then you have the totally reliable ISO-8601 format (YYYYMMDD
) which works for anylanguage and date format setting in SQL Server:
如果由于某种原因这不起作用 - 您总是可以去掉破折号,然后您就拥有完全可靠的 ISO-8601 格式 ( YYYYMMDD
),它适用于 SQL Server 中的任何语言和日期格式设置:
SELECT CAST(REPLACE('2012-08-17', '-', '') AS DATETIME)
回答by CodeLikeBeaker
This will do the trick:
这将解决问题:
SELECT CONVERT(char(10), GetDate(),126)
回答by Randy Worrell
I had a similar situation. Here's what I was able to do to get a date range in a "where" clause (a modification of marc_s's answer):
我也有类似的情况。这是我能够在“where”子句中获取日期范围的方法(对 marc_s 的答案的修改):
where cast(replace(foo.TestDate, '-', '') as datetime)
between cast('20110901' as datetime) and
cast('20510531' as datetime)
Hope that helps...
希望有帮助...
回答by Beyhan
Write a function
写一个函数
CREATE FUNCTION dbo.SAP_TO_DATETIME(@input VARCHAR(14))
RETURNS datetime
AS BEGIN
DECLARE @ret datetime
DECLARE @dtStr varchar(19)
SET @dtStr = substring(@input,1,4) + '-' + substring(@input,5,2) + '-' + substring(@input,7,2)
+ ' ' + substring(@input,9,2) + ':' + substring(@input,11,2) + ':' + substring(@input,13,2);
SET @ret = COALESCE(convert(DATETIME, @dtStr, 20),null);
RETURN @ret
END
回答by dream
if you datatype is datetime of the table.col , then database store data contain two partial : 1 (date) 2 (time)
如果数据类型是 table.col 的日期时间,则数据库存储数据包含两个部分:1(日期)2(时间)
Just in display data use convert or cast.
只是在显示数据中使用 convert 或 cast。
Example:
例子:
create table #test(part varchar(10),lastTime datetime)
go
insert into #test (part ,lastTime )
values('A','2012-11-05 ')
insert into #test (part ,lastTime )
values('B','2012-11-05 10:30')
go
select * from #test
A 2012-11-05 00:00:00.000
B 2012-11-05 10:30:00.000
select part,CONVERT (varchar,lastTime,111) from #test
A 2012/11/05
B 2012/11/05
select part,CONVERT (varchar(10),lastTime,20) from #test
A 2012-11-05
B 2012-11-05