如何从SQL Server中检索YYYY-MM-DD格式的日期?我需要这个工作与SQL Server 2000及更高。是否有一个简单的方法来执行这在SQL Server或它会更容易转换后,我检索的结果集?

我已经阅读了微软Technet上的CAST和CONVERT,但我想要的格式没有列出,改变日期格式也不是一个选项。


当前回答

由于字符串处理是昂贵的,FORMAT更是如此,我很惊讶Asher/Aaron Dietz的响应不是更高,如果不是顶级的;问题是寻找ISO 8601日期,并没有特别要求它作为字符串类型。

最有效的方法可能是以下任何一种(为了完整起见,我已经包括了Asher/Aaron Dietz提出的答案):

所有版本

select  cast(getdate() as date)
select  convert(date, getdate())

2008年及以上

select  convert(date, current_timestamp)

ANSI SQL等效2008和更高

select  cast(current_timestamp as date)

引用:

https://sqlperformance.com/2015/06/t-sql-queries/format-is-nice-and-all-but

https://en.wikipedia.org/wiki/ISO_8601

https://www.w3schools.com/sql/func_sqlserver_current_timestamp.asp

https://learn.microsoft.com/en-us/sql/t-sql/functions/current-timestamp-transact-sql?view=sql-server-ver15

其他回答

对于那些也想要时间部分的人(我想),下面的片段可能会有所帮助

SELECT convert(varchar, getdate(), 120) -- yyyy-mm-dd hh:mm:ss(24h)
SELECT convert(varchar, getdate(), 121) -- yyyy-mm-dd hh:mm:ss.mmm
SELECT convert(varchar, getdate(), 126) -- yyyy-mm-ddThh:mm:ss.mmm
                              --example -- 2008-10-02T10:52:47.513

将GetDate()更改为字符串格式:

SELECT FORMAT(GetDate(), 'yyyy-MM-dd HH:mm:ss')

在你的强制转换链接中,使用样式126:

CONVERT (varchar(10), DTvalue, 126)

这缩短了时间。您要求它在yyyy-mm-dd中,这意味着它必须是字符串数据类型和日期时间。

坦率地说,除非你有充分的理由不这么做,否则我会在客户端上这么做。

由于字符串处理是昂贵的,FORMAT更是如此,我很惊讶Asher/Aaron Dietz的响应不是更高,如果不是顶级的;问题是寻找ISO 8601日期,并没有特别要求它作为字符串类型。

最有效的方法可能是以下任何一种(为了完整起见,我已经包括了Asher/Aaron Dietz提出的答案):

所有版本

select  cast(getdate() as date)
select  convert(date, getdate())

2008年及以上

select  convert(date, current_timestamp)

ANSI SQL等效2008和更高

select  cast(current_timestamp as date)

引用:

https://sqlperformance.com/2015/06/t-sql-queries/format-is-nice-and-all-but

https://en.wikipedia.org/wiki/ISO_8601

https://www.w3schools.com/sql/func_sqlserver_current_timestamp.asp

https://learn.microsoft.com/en-us/sql/t-sql/functions/current-timestamp-transact-sql?view=sql-server-ver15

如果你想在之后再次使用它作为日期而不是varchar,不要忘记将其转换回来:

select convert(datetime,CONVERT(char(10), GetDate(),126))