【问题标题】:How can i obtain the date only from the datetime column? [duplicate]如何仅从日期时间列中获取日期? [复制]
【发布时间】:2013-11-29 10:37:52
【问题描述】:

我有以下查询

SELECT GETDATE()

返回我为 2013-11-16 03:31:07.740 我只想要 DATE 部分并省略 Time 部分。

我用过

select convert(varchar, getdate(), 100) convertResult,100 style union
select convert(varchar, getdate(), 101),101 union
select convert(varchar, getdate(), 102),102 union
select convert(varchar, getdate(), 103),103 union
select convert(varchar, getdate(), 104),104 union
select convert(varchar, getdate(), 105),105 union
select convert(varchar, getdate(), 106),106 union
select convert(varchar, getdate(), 107),107 union
select convert(varchar, getdate(), 108),108 union
select convert(varchar, getdate(), 109),109 union
select convert(varchar, getdate(), 110),110 union
select convert(varchar, getdate(), 111),111 union
select convert(varchar, getdate(), 112),112 union
select convert(varchar, getdate(), 113),113 union
select convert(varchar, getdate(), 114),114  union
select convert(varchar, getdate(), 120),120  union
select convert(varchar, getdate(), 121),121  union
select convert(varchar, getdate(), 126),126  union
select convert(varchar, getdate(), 127),127  union
select convert(varchar, getdate(), 130),130  union
select convert(varchar, getdate(), 131),131
order by 2

但不是任何组合都只给我日期部分。

【问题讨论】:

  • FWIW 我不太喜欢建议的副本。接受和可笑地赞成的答案使用了 SQL Server 2008+ 中不再需要的技术......它也没有解决这个特定问题!它仍然返回时间,它只是设置为午夜......

标签: sql-server sql-server-2008


【解决方案1】:

最有效的方法是将其保持为日期类型,而不是将其转换为字符串:

SELECT CONVERT(DATE, GETDATE());

如果您出于某种原因确实想要字符串输出:

SELECT CONVERT(CHAR(10), GETDATE(), 120);

(没有理由使用VARCHAR,获取字符串特定长度的方法是指定字符串的长度。Please read this post。)

accepted and highly up-voted answer on the proposed duplicate——我相信它最终会解决这个问题,由于旅鼠因素——没有充分解决这个问题。

  1. 它使用的技术对于 SQL Server 2000 和 SQL Server 2005 来说是一种有效的方法,但对于 SQL Server 2008+ 则不是,因为上述转换比进行日期数学更有效(差异可能可以忽略不计,但这是事情的原理)。

  2. 它仍然在输出中返回时间(它只是在午夜而不是现在)。这里的 OP 不希望在输出中包含时间(无论是实时时间还是午夜等)。

【讨论】:

    【解决方案2】:

    因为您使用的是 SQL Server 2008

    SELECT cast(GETDATE() as DATE)
    

    【讨论】:

    • +1 这比我的简洁多了,但我确实会喋喋不休
    • 大声笑@AaronBertrand,愿你的“喋喋不休”继续下去,我相信它对我们许多人都有启发!
    【解决方案3】:
    SELECT CONVERT(VARCHAR(10), GETDATE(), 101) 
    

    退货

    11/15/2013
    
    SELECT CONVERT(VARCHAR(10), GETDATE(), 120)
    

    退货

    2013-11-15
    

    【讨论】:

      猜你喜欢
      • 2016-02-23
      • 1970-01-01
      • 1970-01-01
      • 2021-02-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-04-04
      • 2018-10-09
      相关资源
      最近更新 更多