可以datetime类型的sql server只保留时间吗?

时间:2016-07-20 13:05:01

标签: sql asp.net sql-server database

我试图以格式存储时间

  

05:00 PM

在数据库中。但是当我插入数据时,它会自动存储日期以及

  

2016-07-20 17:00:00.000

我只想要

  

17:00

在数据库中

2 个答案:

答案 0 :(得分:1)

首先,正如评论中所建议的那样,您应该使用time类型而不是datetime

SQL Server中time的格式为:hh:mm:sshh:mm:ss.nnnnnnn。如果您希望时间为AM PM格式,请使用以下内容:

CONVERT(varchar(15),CAST('17:00:00.000' AS TIME),100)

答案 1 :(得分:1)

您无法仅在存储默认日期的日期时间字段中存储时间,如果您在2008年,则使用TIME数据类型。

Exception calling "GetVersionInfo" with "1" argument(s): "C:\Users\bob\AppData\Local\Temp\3\test.txt"
At line:1 char:1
+ [System.Diagnostics.FileVersionInfo]::GetVersionInfo($this.FullName)
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (:) [], MethodInvocationException
    + FullyQualifiedErrorId : FileNotFoundExceptio

for sql 2008

declare @t datetime
select @t=cast(getdate() as time)
print @t
---Jan  1 1900  9:17AM

declare @t time
select @t=cast(getdate() as time)
print @t
---09:17:48.3330000

for 2005

select cast(getdate() as time)
--09:17:25.4400000

您的确切格式

select convert(varchar(10),getdate(),108)
---09:17:33

您还可以使用FORMAT仅存储时间(来自SQl 2012)

select cast(datepart(hour,getdate()) as varchar(10))+':'+ cast(datepart(minute,getdate()) as varchar(10))
---9:17