【问题标题】:SQL convert or cast a varchar to datetimeSQL 将 varchar 转换或强制转换为 datetime
【发布时间】:2013-02-04 12:33:41
【问题描述】:

我有一个表,其中 DATEDEPOT 列为 varchar(20)

里面的信息是这样的:20020101 - 我的意思是YYYYMMDD

我想把它转换成日期时间。

为此,我检查了其他帖子的答案,但对我没有任何帮助。

这是我尝试过的:

select datedepot, cast(datedepot as datetime) as test from DessinsV2

我收到这条消息:

Msg 241,Niveau 16,État 1,Ligne 1。
Échec de la conversion de la date et/ou de l'heure à partir d'une chaîne de caractères。

我试过了:

declare @Madate char(10)
SELECT @MaDate=datedepot from DessinsV2

select convert(datetime,left(@Madate,4)+substring(@Madate,5,2)+right(@Madate,2))as DATEDEPOTTEST from dessinsv2

我得到:

Msg 241,Niveau 16,État 1,Ligne 1
Échec de la conversion de la date et/ou de l'heure à partir d'une chaîne de caractères。

【问题讨论】:

  • 你使用哪个数据库?
  • 这个问题需要(需要)一个 SQL 引擎标签(MySQL、PostgreSQL 等),但尽管要求澄清,但仍未提供。我现在会尝试将其标记为缺少minimal reproducible example,但如果它已关闭,它肯定可以在编辑后再次重新打开。

标签: sql type-conversion


【解决方案1】:

这是否在您的机器上运行?

DECLARE @var as nvarchar(20)
SELECT @var = '20020101'
SELECT CONVERT(datetime, @var)

此查询适用于我,但如果我使用格式为“DDMMYYYY”的日期字符串则无效。

有关日期时间的更多信息,请参阅http://msdn.microsoft.com/en-us/library/ms187819.aspx

【讨论】:

    【解决方案2】:
    select '20020101' as orignal_date,
           cast('20020101' as datetime) as converted_date
    

    这对我很好,请检查。

    【讨论】:

      【解决方案3】:

      您必须为转换函数指定日期输入格式,例如:

      select datedepot, convert(datetime, datedepot,112) as test from DessinsV2

      请参阅:http://msdn.microsoft.com/es-es/library/ms187928.aspx 了解更多格式。

      【讨论】:

        【解决方案4】:

        感谢大家的帮助。

        我的查询很好,但我查询了“分组依据”,我发现了一些不规则的内容,例如特殊字符或特殊数字。这些信息无法转换。

        所以我忽略了带有奇怪信息的行,我的查询工作正常。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2021-03-26
          • 1970-01-01
          • 2016-12-09
          • 1970-01-01
          • 2017-11-29
          • 1970-01-01
          • 2010-09-09
          • 2021-11-28
          相关资源
          最近更新 更多