将精确的日期时间作为参数发送到SqlDataSource

时间:2011-09-21 11:54:21

标签: .net asp.net sql-server

我想将.Net DateTime作为参数添加到SqlDataSource。我知道如何添加参数,但我需要尽可能精确地添加DateTime。它需要非常精确,因为有些表使用datetime列作为键,如果发送的日期时间不够精确,则连接将无法正常工作。

旧的方式(没有SqlDataSource)是这样的:

SqlCommand cmd = new SqlCommand();
cmd.CommandType = System.Data.CommandType.StoredProcedure;
cmd.CommandText = "PosT2sNwu.RPT_GetFundTransactions";
cmd.Parameters.Add(new SqlParameter("@FromDate", fromDate));

似乎SqlDataSource的参数只接受字符串。

所以问题是:我如何格式化字符串(从.Net DateTime生成),以便它尽可能精确地(最多毫秒,甚至微秒)在存储过程中结束?

3 个答案:

答案 0 :(得分:0)

使用使用SqlParameter作为参数

的重载SqlDbType构造函数
SqlParameter(String, SqlDbType, Int32) 
SqlParameter(String, SqlDbType, Int32, String) 

然后使用MSDN页面上描述的SqlDbType.DateTime作为“日期和时间数据,范围从1753年1月1日到9999年12月31日,精度为3.33毫秒”。

答案 1 :(得分:0)

这有用吗?

http://msdn.microsoft.com/en-us/library/z72eefad.aspx

你应该能够在日期时间调用tostring,结果将包括所有部分,直到毫秒。

答案 2 :(得分:0)

您可以在代码隐藏文件中指定参数类型(如Karel建议,指定DateTime)或通过设置Type属性Type =“DateTime”

来声明参数