我目前遇到一个数据库问题,我需要使用数据库插入操作数据。我目前正在 Visual studio 2012 上使用 C# ASP.NET 制作一个网站,我使用的数据库是 SQL Management 2008。
首先,我目前将 System.Date 存储到字符串中,并将其作为 nvarchar 数据类型存储在数据库中。如果我想获取最新的 10 行,例如 user= 'x',我应该如何执行 SELECT 语句以仅获取我指定的数据?
我目前使用 calander Ajax 工具包存储出生日期等信息,因此保存日期的格式为月/日/年格式。数据也以 nvarchar 形式存储到我的数据库中。如果我想计算 user='x' 的年龄,我应该如何计算?
最佳答案
我认为Jon's comment关于正确存储数据,因为日期时间是正确的:
Why are you storing it as an nvarchar to start with? It's logically a date/time, not a string - so store it as a date/time. Get rid of the string part, and all your formatting problems go away too.
如果可以的话,一定要这样做。
如果由于某种原因您无法更改数据库结构,则可以在 ORDER BY
中使用 CAST
/CONVERT
语句> 子句来得到你想要的:
SELECT TOP 10 *, CAST(yourDateField AS datetime) AS convertedDate
FROM yourTable
WHERE
user='Some user'
ORDER BY CAST(yourDateField AS datetime) DESC
这假设您的 nvarchar 数据可以正确转换为日期时间(如果您使用 Ajax Control Toolkit 日历扩展器,则应该是这样)。
关于asp.net - 不同的日期类型操作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16705575/