【问题标题】:concatenate two columns with date and time in sql?用sql中的日期和时间连接两列?
【发布时间】:2011-02-03 05:07:10
【问题描述】:

我有两列 orderdate(03/02/2011)ordertime(10.34 am) 在其中我必须连接这两列并在另一列中显示为日期时间值(03/02/2011 10:34:16.190)....

有什么建议吗?

【问题讨论】:

标签: sql sql-server tsql sql-server-2008


【解决方案1】:

一般来说,解决方案是将天数添加到其天部分为零的时间值中。您不清楚这两个值的数据类型,但是一种解决方案是:

With Inputs As
    (
    Select '20110302' As DateVal, '10:34 AM' As TimeVal
    )
Select DateAdd(d, DateDiff(d, 0, Cast(DateVal As datetime)), Cast(TimeVal as datetime))
From Inputs 

一个更明确的版本,假设输入是字符串并给出您的确切输入:

Set DateFormat MDY

With Inputs As
    (
    Select '03/02/2011' As DateVal, '10:34 AM' As TimeVal
    )
Select DateAdd(d, DateDiff(d, 0, Cast(DateVal As datetime)), Cast(TimeVal as datetime))
From Inputs

【讨论】:

    【解决方案2】:

    假设您正在使用DATETIME,您需要先转换才能添加。

    SELECT [orderdate] + CONVERT(datetime, [ordertime])
    

    【讨论】:

      【解决方案3】:

      您希望以编程方式或在 sql server 中:

      在 SQL Server 中:

      选择 orderdate + ordertime 作为 'YourColumnName'

      希望对您有所帮助。

      【讨论】:

      • -1 不能使用+ 运算符在 SQL 中添加日期和时间数据类型。
      • 但你可以像 convert(varchar(10),orderdate ,101)+''+convert(varchar(10),ordertime) 那样做'Test'。我刚刚给出了你如何处理这个问题的方法。
      • 你也不会使用字符串。您的结果取决于语言
      【解决方案4】:

      在 MySQL 中,它会像这样工作

      SELECT Concat(orderdate, " ", ordertime) FROM vendors ORDER BY vend_name;
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2020-07-26
        • 1970-01-01
        • 1970-01-01
        • 2021-12-25
        • 1970-01-01
        • 2015-05-07
        • 1970-01-01
        相关资源
        最近更新 更多