SQL Server 2005根据日期时间主键列检索记录时出错
我在 SQL Server 2005 中有一个带有复合主键的表,即外键 (INT) 和日期时间列。
当我运行SQL时,
Select column1 From TABLE where ForeignKey=1 and DateTime='08/26/2010 11:24:36'
如果有这样的记录,则不会返回任何记录。
一种选择是
Select column1 From TABLE where ForeignKey=1 and DateTime>='08/26/2010 11:24:36' and DateTime<'08/26/2010 11:24:37'
但是,似乎...... 我真的必须诉诸这个吗?或者是因为我必须指定直到毫秒? 或者有什么解决办法吗?
请帮忙。提前致谢。
I have a table in SQL Server 2005 with composite primary key, i.e. a foreign key (INT) and DateTime column.
When i run the SQL,
Select column1 From TABLE where ForeignKey=1 and DateTime='08/26/2010 11:24:36'
No record was return when there is such a record.
One option to do is
Select column1 From TABLE where ForeignKey=1 and DateTime>='08/26/2010 11:24:36' and DateTime<'08/26/2010 11:24:37'
But then, it just seems...
Do i really have to resort to this? or it is because i have to specify until millisecond?
Or is there any solutions?
Please help. Thanks in advance.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
是的,您必须将 DateTime 值的精度与毫秒相匹配才能使相等性生效。
您提出的替代方案将会起作用。作为另一个想法,您可以使用 强制转换和转换 来截断您的存储的日期时间精确到秒。但请注意,在 where 子句中使用这些函数将否定优化器在日期时间列上使用任何索引的能力。您必须决定这会对您的特定环境产生什么影响。
编辑:根据下面的评论,我注意到 SQL Server 在比较中似乎没有发现 1 毫秒的差异。这在 2000/2005/2008 环境中是正确的。如果我在 2008 年使用新的 datetime2 数据类型,那么它的工作原理如下预期的。阅读 datetime 数据类型,毫秒部分的精度为圆角:
Yes, you would have to match the precision of the DateTime value to the millisecond for the equality to work.
Your proposed alternative will work. As another idea, you could use a cast and convert to truncate your stored datetime down to the second. Note however that using these functions in the where clause will negate the optimizer's ability to use any index on your datetime column. You'll have to decide what impact that would have in your specific environment.
EDIT: Following up on the comments below, I've noticed that SQL Server does not seem to pick up a 1 millisecond difference in a comparison. This is true in 2000/2005/2008 environments. If I use the new datetime2 datatype in 2008, then it works as expected. Reading up on the datetime datatype, the accuracy of the millisecond portion is rounded:
如果可能的话,不要使用日期时间字段作为键。相反,创建一个不同的键并简单地索引您的日期时间值。
If at all possible don't use a datetime field as your key. Instead create a different key and simply index your datetime value.