如何将SQL Server的timestamp列转换为datetime格式 [英] How to convert SQL Server's timestamp column to datetime format

查看:1772
本文介绍了如何将SQL Server的timestamp列转换为datetime格式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

由于SQL Server返回时间戳,如'2011年11月14日03:12:12:947PM',是否有一些简单的方法可以将字符串转换为日期格式,如Ymd H :i:s'。



到目前为止,我使用

  date ('Ymd H:i:s',strtotime('2011年11月14日03:12:12:947PM')


解决方案

SQL Server的 TIMESTAMP 数据类型具有日期和时间的无任何 / p>

这只是一个连续数字的二进制表示形式 - 它只是确保一行从读取以来没有改变。



在较新版本的SQL Server中,它被称为 RowVersion - 因为这是真的。请参阅 ROWVERSION 上的MSDN文档:


是一种在数据库中公开自动生成的唯一二进制数字的数据类型。 rowversion通常用作版本冲压表行的机制

rowversion数据类型是只是一个递增的数字,
不保留日期或时间
。要记录日期或时间,请使用datetime2
数据类型。


所以你不能将SQL Server TIMESTAMP 转换为日期/时间 - 这不是日期/时间。



但是如果你在说时间戳,但是你真的意味着一个 DATETIME 列,那么你可以使用 CAST和CONVERT 主题。这些被SQL Server定义和支持开箱即用。还没有其他的东西,例如你必须做很多手工投射和连接(不推荐)。



您正在寻找的格式看起来有点像ODBC规范(style = 121):

  DECLARE @today DATETIME = SYSDATETIME()

SELECT CONVERT (VARCHAR(50),@today,121)

给出:

  2011-11-14 10:29:00.470 

SQL Server 2012最终将有一个 FORMAT 功能来执行自定义格式化......


As SQL Server returns timestamp like 'Nov 14 2011 03:12:12:947PM', is there some easy way to convert string to date format like 'Y-m-d H:i:s'.

So far I use

date('Y-m-d H:i:s',strtotime('Nov 14 2011 03:12:12:947PM'))

解决方案

SQL Server's TIMESTAMP datatype has nothing to do with a date and time!

It's just a binary representation of a consecutive number - it's only good for making sure a row hasn't change since it's been read.

In newer versions of SQL Server, it's being called RowVersion - since that's really what it is. See the MSDN docs on ROWVERSION:

Is a data type that exposes automatically generated, unique binary numbers within a database. rowversion is generally used as a mechanism for version-stamping table rows. The rowversion data type is just an incrementing number and does not preserve a date or a time. To record a date or time, use a datetime2 data type.

So you cannot convert a SQL Server TIMESTAMP to a date/time - it's just not a date/time.

But if you're saying timestamp but really you mean a DATETIME column - then you can use any of those valid date formats described in the CAST and CONVERT topic in the MSDN help. Those are defined and supported "out of the box" by SQL Server. Anything else is not supported, e.g. you have to do a lot of manual casting and concatenating (not recommended).

The format you're looking for looks a bit like the ODBC canonical (style = 121):

DECLARE @today DATETIME = SYSDATETIME()

SELECT CONVERT(VARCHAR(50), @today, 121)

gives:

2011-11-14 10:29:00.470

SQL Server 2012 will finally have a FORMAT function to do custom formatting......

这篇关于如何将SQL Server的timestamp列转换为datetime格式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆