简体   繁体   English

在SQL Server 2008中获取日期

[英]Fetching date in SQL Server 2008

How to split date in select query of SQL Server 2008 ? 如何在SQL Server 2008的选择查询中拆分日期? If you feed you feed current date in database and the type of that column in database is date time then It will store the date as well as time.If any one want to fetch only the date part from that column then what can he do. 如果您在数据库中输入当前日期,并且数据库中该列的类型是日期时间,则它将存储日期和时间。如果有人只想从该列中获取日期部分,那么他可以做什么。

I can use this query but it should not work. 我可以使用此查询,但它不起作用。

SELECT DonorName, DATE(DateOfDonation) AS DateOfDonation 
FROM CreateDonorDetail;

it give error- 它给错误-

'DATE' is not a recognized built-in function name. 'DATE'不是公认的内置函数名称。

SQL Server 2008 has a DATE datatype - but it's disabled if your database was upgraded from a SQL Server 2005, and you didn't change the database compatibility level . SQL Server 2008 具有 DATE数据类型-但是,如果您的数据库是从SQL Server 2005升级的,并且未更改数据库兼容性级别 ,则将其禁用。

Check your compatibility level like this: 像这样检查您的兼容性级别:

SELECT name, compatibility_level
FROM sys.databases
WHERE name = '-Your-database-name-here-'

If this compatibility level is 90 , it's set to SQL Server 2005 and you won't be able to use DATE . 如果此兼容性级别为90 ,则将其设置为SQL Server 2005,并且您将无法使用DATE Update your compatibility level to 100: 将兼容性级别更新为100:

ALTER DATABASE AdventureWorks2012
SET COMPATIBILITY_LEVEL = 100

Now you should be able to use DATE : 现在您应该可以使用DATE

SELECT 
    DonorName, 
    CAST(DateOfDonation AS DATE) AS DateOfDonation 
FROM CreateDonorDetail;

Cast as Date type: 转换为Date类型:

SELECT DonorName, Cast(DateOfDonation as Date) AS DateOfDonation 
FROM CreateDonorDetail;

在SQL Server 2008之前,您可能会使用类似以下的内容:

SELECT DonorName, CAST(FLOOR(CAST(DateOfDonation AS FLOAT)) AS datetime) AS DateOfDonation   FROM CreateDonorDetail

DECLARE @DateTime DATETIME 宣告@DateTime DATETIME

SELECT @DateTime = '2010/05/20 11:21:13' SELECT @DateTime ='2010/05/20 11:21:13'

SELECT CONVERT(VARCHAR(10),@DateTime ,105) AS Date SELECT CONVERT(VARCHAR(10),@ DateTime,105)AS日期

the result will be in dd-mm-yyyy format (105) 结果将为dd-mm-yyyy格式(105)

  • Hope it will helps 希望这会有所帮助

mark as answer if it helped 标记为答案是否有帮助

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM