I work on an ASP.NET web forms project; I can't get data between two times (time from and time to) on datetime column.
C#function
public DataTable GetDataForSearch(string datelogged, string FromTime, string ToTime)
{
string response = string.Empty;
SqlCommand cmd = new SqlCommand();
DataTable dt = new DataTable();
try
{
conn.Open();
cmd.Connection = conn;
cmd.CommandText = "select datelogged AS EntredDatetime, Doc_type AS OrderType, Printer_name, BranchID AS BranchCode, Status, id from Print_Report where cast(datelogged as date)=@datelogged and and FORMAT(CAST(datelogged AS DATETIME), 'HH:mm')>'@FromTime' AND FORMAT(CAST(datelogged AS DATETIME), 'HH:mm')<@ToTime";
cmd.CommandType = CommandType.Text;
cmd.CommandTimeout = 50000;
cmd.Parameters.AddWithValue("@datelogged", datelogged);
cmd.Parameters.AddWithValue("@FromTime", FromTime);
cmd.Parameters.AddWithValue("@ToTime", ToTime);
SqlDataAdapter sda = new SqlDataAdapter(cmd);
sda.Fill(dt);
}
catch (Exception ex)
{
response = ex.Message;
}
finally
{
cmd.Dispose();
conn.Close();
}
return dt;
}
When I try from SQL Server, it return 2 rows:
select
datelogged as EntredDatetime, Doc_type as OrderType,
Printer_name, BranchID as BranchCode, Status, id
from
Print_Report
where
BranchID = '10207'
and cast(datelogged as date) = '2010-07-05'
and Doc_type = 'BP'
and format(cast(datelogged as DATETIME), 'HH:mm') > '13:30'
and format(cast(datelogged as DATETIME), 'HH:mm') < '14:00'
Expected result:

I modified query to as below :
cmd.CommandText = "select datelogged AS EntredDatetime, Doc_type AS OrderType, Printer_name, BranchID AS BranchCode, Status, id from Print_Report where BranchID=@BranchCode and cast(datelogged as date)=@datelogged and Doc_type=@OrderType and FORMAT(CAST(datelogged AS DATETIME), 'HH:mm')>='@FromTime' AND FORMAT(CAST(datelogged AS DATETIME), 'HH:mm')<='@ToTime'";
but still not get any result so what i do to solve issue
Always declare the type of parameter you're passing into SQL. Don't rely on sql to infer it. Also make a habit of wrapping your db connection in a
Usingblock.You'll need to add code for the @branch and @ordertype parameters as well.
Your SQL would look like the below. When writing SQL, most mistakes can be managed by consistently formatting your SQL while you write it. Parameters do not need to be wrapped in quotes when you declare the data type of the param like I have above. It handles all that for you. Rather than comparing the date separately, I opted to pass the times in as Time data type and then cast them to datetime inside the query. From there, you can add two date times together with the
+and then do your comparison the same way. If you decide to pass your to/from values in as datetime then just remove the declare line at the top.You could use
BETWEENin theWHEREclause but that's at your discretion.