如何从两个不同的日期从数据库中找到今天的数据?

时间:2014-11-14 06:55:55

标签: c# sql-server

我有一个数据库ShiftChange,字段是

Fromdate='09/11/2014', Todate='11/11/2014',Shift='MG' and Month='11'(dd/MM/YYYY format)
Fromdate='11/11/2014', Todate='15/11/2014',Shift='AF' and Month='11

我想从今天的表中找到今天的转变。我试过这个,

DateTime today = DateTime.Today; // As DateTime
string s_today = today.ToString("dd/MM/yyyy");//system date converted to given format
int month = DateTime.Now.Month;
string str = "Select Min(Fromdate), Max(Todate)  From ShiftChange where Month='" + month + "'";
SqlDataReader dr = conn.query(str);
if (dr.Read())
{
    string mindate = dr[0].ToString();
    string maxdate = dr[1].ToString();
    string str3 = "select Shift from ShiftChange where '" + s_today + "' >= '" + mindate + "' and  '" + s_today + "' <= '" + maxdate + "' and Month='"+month+"'";//checks current shift type of selected date.
    SqlDataReader dr3 = conn.query(str3);
    if (dr3.Read())
    {
        string shiftid = dr3[0].ToString();
    }

此处连接是我的connection类,query是我的(sqldatareader dr)方法。当我运行此查询时,我得到shiftName 'MG'但实际上今天的shiftName记录是' AF'但它没有得到。我希望这是我的查询问题。请告诉我错误

2 个答案:

答案 0 :(得分:0)

首先,您应该对查询进行参数化,或者您可以准备sql存储过程并在代码中使用该存储过程。我在这里给你存储过程的sql代码。

declare @month varchar(50) = '11'
declare @mindate varchar(50)
declare @maxdate varchar(50)
declare @date varchar(50)

select @mindate=min(fromdate),@maxdate = max(todate)
from ShiftChange Where Month = @month

select TOP 1 Shift From ShiftChange
WHERE @date>= fromdate and todate<=@date
and month = @month
order by todate desc

顺便说一句,在处理日期时使用数据类型日期或日期时间总是更好。

答案 1 :(得分:0)

我用@ Mukund的帮助解决了这个问题。我在我的项目中应用了他的代码,

DateTime today = DateTime.Today; // As DateTime
string s_today = today.ToString("dd/MM/yyyy");
int month = DateTime.Now.Month;
string str = "Select Min(Fromdate), Max(Todate)  From ShiftChange where Month='" + month + "'";
SqlDataReader dr = conn.query(str);
if (dr.Read())
{
string mindate = dr[0].ToString();
string maxdate = dr[1].ToString();
string str3 = "select TOP 1 Shift From ShiftChange WHERE '"+s_today+"'>=Fromdate and Todate>='"+s_today+"' and month = '"+month+"' order by Todate desc";
SqlDataReader dr3=conn.query(str3);
if(dr3.Read())
{
string shift = dr3[0].ToString();
}