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

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


当前回答

如果你的源日期格式乱七八糟,试试下面的方法:

select
convert(nvarchar(50),year(a.messedupDate))+'-'+
(case when len(convert(nvarchar(50),month(a.messedupDate)))=1 
    then '0'+ convert(nvarchar(50),month(a.messedupDate))+'-' 
    else convert(nvarchar(50),month(a.messedupDate)) end)+
(case when len(convert(nvarchar(50),day(a.messedupDate)))=1 
    then '0'+ convert(nvarchar(50),day(a.messedupDate))+'-'
    else convert(nvarchar(50),day(a.messedupDate)) end) 
from messytable a

其他回答

SELECT Code,Description FROM TABLE

-- This will Include only date part of 14th March 2010. Any date with date companents will not be considered.
WHERE ID= 1 AND FromDate >= CONVERT(DATETIME, '2010-02-14', 126) AND ToDate <= DATEADD(dd, 1, CONVERT(DATETIME, '2010-03-14', 126))

-- This will Include the whole day of 14th March 2010
--WHERE ID= 1 AND FromDate >= CONVERT(DATETIME, '2010-02-14', 126) AND ToDate < DATEADD(dd, 1, CONVERT(DATETIME, '2010-03-14', 126))

您所需要的表格在图书在线文档中列出。

http://msdn.microsoft.com/en-us/library/aa226054 (SQL.80) . aspx

例如,尝试以下方法:

select convert(varchar,getDate(),120)
select convert(varchar(10),getDate(),120)

从SQL Server 2008你可以这样做:CONVERT(date,getdate())

由于字符串处理是昂贵的,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

带有格式说明符120的convert函数将为您提供格式“yyyy-MM-dd HH:mm:ss”,因此您只需将长度限制为10以只获得日期部分:

convert(varchar(10), theDate, 120)

然而,日期格式化通常在表示层而不是在数据库或业务层更好。如果从数据库返回格式化的日期,那么如果客户机代码需要对其进行任何计算,则必须再次将其解析为日期。

c#中的例子:

theDate.ToString("yyyy-MM-dd")