我的代码中有一个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中运行该过程没有问题,但当传递DateTime时,查询始终为空。有什么建议吗?
发布于 2013-05-06 22:30:14
我使用SQL Server2008 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 + ".");
}它很简单的起作用。
发布于 2015-05-05 20:43:46
下面是我为Datetime创建SqlParameter的代码;对于SQL Server2008,我们将值作为datetime2传递,因为只要它在目标类型的范围内,SQL就会隐式地从datetime2转换为其他date类型……
// 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);发布于 2013-05-06 21:26:33
由于您的参数在日期和月份中包含零,因此parts...sql服务器会将其转换,但不会与您的日期匹配。即,
如果DATETIME.now()返回'2000-03-03 04:05:01'...它被强制转换为2000-3-3,不包括zeros...so。您还需要指定零以匹配您的日期。
https://stackoverflow.com/questions/14124887
复制相似问题