根据日期字段筛选表时出错

本文关键字:出错 筛选 字段 日期 | 更新日期: 2023-09-27 18:19:58

我使用此代码按日期字段筛选表(表中)这是我的代码:

public double Mounthcost()
    {
        DateTime today = DateTime.Now;
        PersianCalendar persianCalendar = new PersianCalendar();
        int yearPersian = persianCalendar.GetYear(today);
        int monthPersian = persianCalendar.GetMonth(today);
        DateTime firstDayOfMonth = persianCalendar.ToDateTime(yearPersian, monthPersian, 1, 0, 0, 0, 0);
        int daysInMonth = persianCalendar.GetDaysInMonth(yearPersian, monthPersian);
        DateTime lastDayOfMonth = firstDayOfMonth.AddDays(daysInMonth - 1);
        //try
        //{
            SqlDataReader DR = ExecuteReader(System.Data.CommandType.Text, "Select Sum(Price) From Tbl_Cost Where Dat Between" + firstDayOfMonth + "AND" + lastDayOfMonth);
            if (DR.Read())
            {
                Mouth_Cost = Double.Parse(DR[0].ToString());
            }
            return Mouth_Cost;
        //}
        //catch
        //{
        //    return 0;
        //}
    }

这个错误:

在上下文中指定的非布尔类型的表达式,其中需要条件,接近"between10"。

根据日期字段筛选表时出错

您的SQL查询中缺少空格

SqlDataReader DR = ExecuteReader(System.Data.CommandType.Text, "Select Sum(Price) From Tbl_Cost Where Dat Between " + firstDayOfMonth + " AND " + lastDayOfMonth);

注意BETWEEN和and后面的空格。

感谢HABO:)使用这个:

SqlDataReader DR = ExecuteReader(System.Data.CommandType.Text, "Select Sum(Price) From Tbl_Cost Where Dat Between @F AND @L", new SqlParameter[]
            {
                new SqlParameter("@F", firstDayOfMonth),
                new SqlParameter("@L", lastDayOfMonth),
            }

是对的。。。