将DateTime拆分为T-SQL中的两列

时间:2013-07-02 17:10:14

标签: sql-server tsql split

我有一个日期时间字段(例如2013-07-02 01:14:32.000),我正在尝试将其分成两列,别名列名称为“添加日期”和“添加时间:”。我只想查看当前日期之前4天内所有数据的结果。我也希望减少微秒。这是一个简单的解决方案吗?我还在学习SQL Server Management Studio 2008的绳索。任何人都可以编辑我的查询以显示正确的输出吗?

现有查询:

  Select as_key AS [Key:], as_name AS [Server Name:], as_introdate AS [Date Added:]
  from AutomationStations
  Order By [Date Added:] desc

现有查询的示例输出:

  Key: 0001
  Server Name: Server1
  Date Added: 2013-07-02 01:14:32.000

3 个答案:

答案 0 :(得分:1)

或者转换为Date和Time数据类型的替代方法..

SELECT 
    as_key AS 'Key:', 
    as_name AS 'Server Name:',
    CAST(as_introdate AS DATE) 'Date Added:',
    CAST(as_introdate AS TIME(0)) AS 'Time Added:' 
FROM AutomationStations
WHERE DATEDIFF(DAY,as_introdate,GETDATE()) <= 4
ORDER BY as_introdate DESC

答案 1 :(得分:0)

built-in date formats中提取所需部分的最简单方法:

SELECT 
    as_key AS [Key:], 
    as_name AS [Server Name:],
    CONVERT(VARCHAR(10),as_introdate,101) AS [Date Added:],
    CONVERT(VARCHAR(8) ,as_introdate,108) AS [Time Added:]
FROM AutomationStations
WHERE DATEDIFF(d,as_introdate,GETDATE()) <= 4
ORDER BY as_introdate DESC

答案 2 :(得分:-1)

CONVERT(DATE, YOUR_SELECTED_DATETIME) AS DATE,
CONVERT(TIME, YOUR_SELECTED_DATETIME) AS TIME

这样可以保留数据类型。