【发布时间】:2011-09-28 01:49:35
【问题描述】:
我有一张表格,其中的日期时间格式为:
2011-07-01 15:17:33.357
当我对对象执行 .ToString() 时,我正在使用 c# DateTime,我得到的 DateTime 格式为:
04/07/2011 06:06:17
我想知道如何正确传递正确的 DateTime,因为当我运行代码中的 SQL 时它不起作用(即选择正确的 DateTime)。我无法使用 SQL 分析器。
这是代码:
//looks to if a user has had any activity in within the last time specified
public bool IsUserActivitySinceSuppliedTime(int userId, DateTime since)
{
//get everything since the datetime specified [usually 5 hours as this is
//how long the session lasts for
string sql = "SELECT * FROM tbl_webLogging WHERE userid = @userid AND DateAdded > @sinceDateTime";
SqlParameter sinceDateTimeParam = new SqlParameter("@sinceDateTime", SqlDbType.DateTime);
sinceDateTimeParam.Value = since;
SqlCommand command = new SqlCommand(sql);
command.Parameters.AddWithValue("@userid", userId);
command.Parameters.Add(sinceDateTimeParam);
using (SqlDataReader DataReader = GetDataReader(command))
{
if (DataReader.HasRows)
{
return true;
}
else
{
return false;
}
}
}
更新************************
我在数据上运行了以下内容:
SELECT * FROM tbl_webLogging
WHERE userid = 1
AND DateAdded > '2011-07-01 07:19:58.000'
和
SELECT * FROM tbl_webLogging
WHERE userid = 1
AND DateAdded > '04/07/2011 07:19:58'
一个返回 53 条记录,另一个返回 69 条记录。怎么会这样?当我将 DateTime (04/07/2011 07:19:58) 从 c# 传递到 SQL 时,根本没有记录显示!
【问题讨论】:
-
表中“添加日期”列的类型是什么?是日期时间吗?还是某种 varchar?
-
您能否确认
DateAdded的类型为datetime,而不是[n]varchar(x)之类的类型? -
那么为什么 c# datetime 会返回 0 条记录呢? (调试器说它是'04/07/2011 07:19:58')@Maras 数据类型是日期时间......
-
您在运行时签入调试器时的用户 ID 是 1 吗?只是检查。
-
好吧,对于 sql 示例,您使用的两个日期不一样 :) --- 可能是错字?然后首先使用 7 月 1 日,第二个使用 7 月 4 日。对于c#代码:你确定你传入的值是正确的吗?