我在SQL Server中有一个看起来像这样的DateTime
2017-02-07 09:18:25.633
现在来自C#,即使在sql中使用SSMS编写查询,我也在做范围如
where WebDateTime between '2/7/2017 8:19' and '2/7/2017 9:19'
然而这是不正确的,因为我没有使用军事时间(不确定是否需要,也不是AM / PM ......因此这条线无法给出结果
where WebDateTime between '2/7/2017 8:19' and '2/7/2017 1:19'
因此8:19到9:19工作,但不是8:19到1:19,我需要做什么才能用"类型"来修复范围。我有约会时间吗?
答案 0 :(得分:0)
使用字符串可以导致SQL注入。相反,使用这样的代码:
using (var connection = new SqlConnection("your connection string here..."))
{
using (var command = new SqlCommand())
{
SqlDataReader reader;
command.Connection = connection;
// Next command is your query.
command.CommandText = "SELECT * FROM MyTable WHERE WebDateTime BETWEEN @Date1 AND @Date2";
command.CommandType = CommandType.Text;
var date1 = new SqlParameter("Date1", SqlDbType.Date);
var date2 = new SqlParameter("Date2", SqlDbType.Date);
date1.Value = new DateTime(2017, 2, 7, 20, 19, 0);
date2.Value = new DateTime(2017, 2, 7, 1, 19, 0);
command.Parameters.Add(date1);
command.Parameters.Add(date2);
connection.Open();
reader = command.ExecuteReader();
// Data is accessible through the DataReader object here.
}
}