1

我的代码中有一个DateTime组件,我想将它用于我的 SQL Server 数据库中的查询。

插入这个组件的时候,好像没有问题,但是查询smalldatetime值的时候,就是不知道怎么做。数据集始终为空。

cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandText = "ReadDates"; 

dataset = new DataSet();

SqlParameter parameter = new SqlParameter("@date", SqlDbType.SmallDateTime);
parameter.Value = DateTime.Now();
cmd.Parameters.Add(parameter);

dataAdapter = new SqlDataAdapter(cmd);
dataAdapter.Fill(dataset);
return dataset;

这是在我的存储过程中:

select * from TableDates
where ValueDate <= @date

因此,当以这种格式输入参数时,我在 SQL Server Management Studio 中运行该过程没有问题:'2000-03-03 04:05:01',但是当传递 a 时DateTime,查询始终为空。有什么建议么?

4

3 回答 3

2

我使用 SQL Server 2008 R2 Express 进行了尝试。

这是我编写的示例存储过程:

CREATE PROCEDURE [dbo].[ShowGivenSmallDateTimeValue] 
    @givenSmallDateTime smalldatetime
AS
BEGIN
    -- SET NOCOUNT ON added to prevent extra result sets from
    -- interfering with SELECT statements.
    SET NOCOUNT ON;

    -- Simply return the given small date time value back to sender.
    SELECT @givenSmallDateTime
END

这是执行该过程的 C# 代码:

var connectionBuilder = new SqlConnectionStringBuilder();
connectionBuilder.DataSource = "localhost\\sqlexpress";
connectionBuilder.IntegratedSecurity = true;

var now = DateTime.UtcNow;

using (var connection = new SqlConnection(connectionBuilder.ConnectionString))
using (var command = new SqlCommand())
{
    command.Connection = connection;
    command.CommandType = CommandType.StoredProcedure;
    command.CommandText = "ShowGivenSmallDateTimeValue";
    command.Parameters.Add(new SqlParameter("@givenSmallDateTime", SqlDbType.SmallDateTime) { Value = now });

    connection.Open();
    var result = (DateTime)command.ExecuteScalar();
    var difference = result - now;

    Console.WriteLine("Due to the smalldatetime roundings we have a difference of " + difference + ".");
}

它很有效。

于 2013-05-06T14:30:13.800 回答
0

这是我为日期时间创建 SqlParameter 的代码;对于 SQL Server 2008,我们将值作为 datetime2 传递,因为 SQL 会从 datetime2 隐式转换为所有其他日期类型,只要它在目标类型的范围内......

            // Default conversion is now DateTime to datetime2. The ADO.Net default is to use datetime. 
            // This appears to be a safe change as any datetime parameter will accept a datetime2 so long as the value is within the
            // range for a datetime. Hence this code is acceptable for both datetime and datetime2 parameters, whereas datetime is not 
            // (because it doesn't handle the full range of datetime2).
            SqlParameter sqlParam = new SqlParameter(name, SqlDbType.DateTime2);
于 2015-05-05T12:43:45.777 回答
-2

由于您的参数在日期和月份部分中包含零...sql server 将其转换但与您的日期不匹配....即,

如果 DATETIME.now() 返回 '2000-03-03 04:05:01'... 它被转换为 2000-3-3 不包括零...所以您还需要指定零以匹配您的日期。

于 2013-05-06T13:26:33.240 回答