如何将DateTime转换为字符串?

时间:2014-01-27 10:33:47

标签: c# sql

我有一个需要3个字符串的方法:

public <List> MethodName(string date1, string date2, string number)
{
  //
}
我的数据库date1date2中的

存储为DateTime,数字存储为Int,那么我将如何编写一个基于这三个搜索的SQL查询参数?

我已将date1date2转换为:

DateTime firstdate = Convert.ToDateTime(date1);
string fdate = firstdate.ToLongDateString();
  DateTime seconddate = Convert.ToDateTime(date1);
string sdate = seconddate .ToLongDateString();

我的SQL查询是:

  SELECT * From TableName 
  WHERE [Time] > @date1 AND 
  [Time] < @date2 AND [StaffCode] =@StaffCode;

command.Parameters.AddWithValue("@date1", fdate);
command.Parameters.AddWithValue("@date2", sdate );

command.Parameters.AddWithValue("@StaffCode", number);
conn.Open();
        SqlDataReader reader = command.ExecuteReader();
        while (reader.Read())
        { get the data ...} 

我确信我的SQL查询错误。

2 个答案:

答案 0 :(得分:5)

由于您的数据库列已经是强类型的,因此在将它们绑定到查询之前,只需确保将C#参数分别键入为System.DateTimeintSystem.Int32)。那么你的sql就是:

SELECT col1, col2, col3
FROM TableName 
WHERE [Time] > @date1 AND 
      [Time] < @date2 AND [StaffCode] =@StaffCode;

如果您允许包含日期,则可以使用BETWEEN,即

WHERE [Time] BETWEEN @date1 AND @date2 
    AND [StaffCode] = @StaffCode

即。完全避免convert a Date to a string的需要。尽可能尝试在C#和SQL代码中保持强大的类型系统 - 这将在转换过程中节省很多痛苦。例如如果可能,请查看是否可以将签名更改为:

public List<MethodName>(DateTime date1, DateTime date2, int number)
{
  // Bind the DateTimes, not a string!
  command.Parameters.AddWithValue("@date1", date1);
  command.Parameters.AddWithValue("@date2", date2);
  command.Parameters.AddWithValue("@StaffCode", number);

修改不要使用SELECT * - 使用SELECT Col1, Col2, ...

答案 1 :(得分:0)

转换:

             DateTime firstdate = Convert.ToDateTime(date1);
             string fdate = firstdate.ToString("yyyy-MM-dd");

             DateTime firstdate2 = Convert.ToDateTime(date2);
             string fdate2 = firstdate2.ToString("yyyy-MM-dd");

SQL查询:

           @"SELECT * From TestTable WHERE Time BETWEEN CONVERT(Date,@date1) AND CONVERT(Date,@date2) AND StaffCode=CONVERT(int,@StaffCode)"
           command.Parameters.AddWithValue("@date1", fdate);
           command.Parameters.AddWithValue("@date2", fdate2);
           command.Parameters.AddWithValue("@StaffCode", number);