如何向具有索引值的日期时间字段添加时间?
如何使用索引值向 datetime
字段添加时间?
我的 RDBMS 是 SQL Server 2008 R2。
我想从中午开始使用 datetime
字段,对于每条记录,采用中午的基值并添加 15 秒并将其设置为记录。
示例
Record 1: DateTime Value = '12:00:00 pm'
Record 2: DateTime Value = '12:00:15 pm'
Record 3: DateTime Value = '12:00:30 pm'
...n...
我尝试使用 UPDATE 查询,但无法将其编入索引。我觉得这可能需要一个功能,但我不确定。
有想法吗?
尊敬的
雷
How do I add time to a datetime
field with an indexing value?
My RDBMS is SQL Server 2008 R2.
I want to start at noon for a datetime
field and for every record, take the base value of noon and add 15 seconds and set it for the record.
Example
Record 1: DateTime Value = '12:00:00 pm'
Record 2: DateTime Value = '12:00:15 pm'
Record 3: DateTime Value = '12:00:30 pm'
...n...
I toyed with a UPDATE query, but I couldn't get it to index. I'm feeling this might require a function, but I'm not sure.
Ideas?
Respectfully,
Ray
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
假设您有一个表
YourTable
,其中包含datetime
列Value
,您需要用每行递增 15 秒的日期时间值填充该表。这里我使用列 ID 来指定行的顺序。Assuming that you have a table
YourTable
with adatetime
columnValue
that you need to fill with a datetime value incremented by 15 seconds for each row. Here I use a column ID to specify the order of the rows.使用递归 CTE(通用表表达式),您可以很容易地做到这一点:
请注意:您需要确保自己在达到默认最大递归深度 100 之前停止递归(这就是我使用
RowNum
列) - 否则,SQL Server 会大声而清晰地告诉您它不喜欢这种递归 CTE :-)这会产生以下输出:
因此,如果您有像这样没有时间的
DATETIME
值:您可以轻松地从递归 CTE 向其添加时间值(您甚至可以调整它以仅返回
TIME
并将其添加到您的DATETIME
列):With a recursive CTE (Common Table Expression) you could do this pretty easily:
Mind you: you need to make sure yourself to stop the recursion before the default max recursion depth of 100 has been reached (that's what I use the
RowNum
column for) - otherwise, SQL Server will tell you loud and clear that it doesn't like this recursive CTE :-)This produces an output of:
So if you have a
DATETIME
value that has no time like this:you could easily add time values to it from your recursive CTE (you could even adapt it to return only
TIME
and add that to yourDATETIME
column):查看 DATEADD 函数,这可能会对您有所帮助。
http://msdn.microsoft.com/en-us/library/ms186819.aspx
Look at the DATEADD function and this may help you.
http://msdn.microsoft.com/en-us/library/ms186819.aspx