在SQL Server 2008中创建日期 [英] Creating Date in SQL Server 2008

查看:129
本文介绍了在SQL Server 2008中创建日期的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在SQL Server 2008中是否有类似于 DATEFROMPARTS(年,月,日)的内容?我想使用当前年份和月份创建一个日期,但是我自己的一个月的日子。这需要在一行中完成,以便在计算的列公式中使用。

Is there something similar to DATEFROMPARTS(year, month, day) in SQL Server 2008? I want to create a date using the current year and month, but my own day of the month. This needs to be done in one line in order to be used in a computed column formula.

例如(我不知道它是否有效,因为我没有SQL Server 2012):

For Example (I'm not sure if it works because I do not have SQL Server 2012):

DATEFROMPARTS(YEAR(GETDATE()), MONTH(GETDATE()), 3)

有没有办法在SQL Server 2008中执行此操作?

Is there a way to do this in SQL Server 2008?

DATEFROMPARTS似乎只在SQL Server 2012中可用(link)

DATEFROMPARTS Seems only available in SQL Server 2012 (link)

推荐答案

使用您的示例中的 3 可以这样做:

Using the 3 from your example, you could do this:

dateadd(dd, 3 -1, dateadd(mm, datediff(mm,0, current_timestamp), 0))

它可以通过查找纪元日期后的月份数,将这些月份添加到纪元日期,然后添加所需数量几天之前的结果。这听起来很复杂,但是它建立在在SQL Server 2008中添加的 Date (而不是DateTime)类型之前截断日期的规范。

It works by finding the number of months since the epoch date, adding those months back to the epoch date, and then adding the desired number of days to that prior result. It sounds complicated, but it's built on what was the canonical way to truncate dates prior to the Date (not DateTime) type added to Sql Server 2008.

您可能会看到其他答案建议建立日期字符串。我敦促你避免这种技术。使用字符串可能会更慢,而且替代日期排序/格式存在一些潜在的缺陷。

You're probably going to see other answers here suggesting building date strings. I urge you to avoid that technique. Using strings is likely to be much slower, and there are some potential pitfalls with alternative date collations/formats.

这篇关于在SQL Server 2008中创建日期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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