简体   繁体   中英

Why is this C# date comparison with SQL datetime not returning results?

I know that records exist between this date range in SQL, but I have tried various formats and even made the range much larger and this still does not return results. What am I doing incorrectly in this query that is causing no records to be returned? Thanks for the help.

DateTime today = DateTime.Now;
DateTime tomorrow = today.AddDays(1);
DateTime yesterday = today.AddDays(-1);

DateTime dt = DateTime.Now;
string yesterdayString = yesterday.ToString("yyyy-MM-dd HH:mm:ss");
string tomorrowString = tomorrow.ToString("yyyy-MM-dd HH:mm:ss");

int itemNum = 0;
string query = "select DocID, CNo, DocType, DocNumber from errordata where cno = '" + cno + "' and createddate > '" + yesterdayString + "' and createddate < '" + tomorrowString + "' order by '" + sorton + "'desc";

the query you are creating is missing the FROM clause. I would expect you are getting an exception.

If you use parameterized queries you will not have this problem. See : http://www.csharp-station.com/Tutorial/AdoDotNet/lesson06

your query should look like this :

@"SELECT VALUE Contact FROM AdventureWorksEntities.Contacts 
            AS Contact WHERE Contact.LastName = @ln" ;

notice the @ placeholder for the parameters then you can do this :

// 2. define parameters used in command object
SqlParameter param  = new SqlParameter();
param.ParameterName = "@City";
param.Value         = inputCity;

// 3. add new parameter to command object
cmd.Parameters.Add(param);

// get data stream
reader = cmd.ExecuteReader();

but the parameter value can be a normal DateTime Value like say DateTime.Today. this should get you started.

Also check the exceptions you might get. Invalid sql will throw exceptions. Catch them and correct the sql if needed.

You could try something like the following:

string query = "SELECT DocID, CNo, DocType, DocNumber "+
               "FROM tableName "+
               "WHERE cno = @cno AND "+
               "CreatedDate BETWEEN @yesterday AND @tomorrow";

var sqlCommand = new SqlCommand(query, connectionString);

sql.Parameters.Add("@cno", cno);
sql.Parameters.Add("@yesterday", yesterday);
sql.Parameters.Add("@tomorrow", tomorrow);

I think that your problem is the missing FROM . Furthermore, I wrote your query using parameters, which prevents sql injections.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM