SQL Query for simple reservation system - c#

I have a simple reservation system. ReservationObject is a flat structure and consist of StartDate, EndDate, Resource and other attributes.
I am trying to get a report of Resource usage. For this report, I am simply querying StartDate to find all the reservations with report query range and counting them.
Example SQL query is..
"SELECT *
FROM RequestsQueueObjects
WHERE PODObjectID='" +cPOD.PODObjectID + "'
and StartDateTime >= '" + StartDate + "'
and StartDateTime <= '" + EndDate + "'";
There is an issue with my design. If I have a reservation that starts on 1/1/2015 and ends on 1/15/2015 , This will not show up on report for 1/2/2015 to 1/7/2015
Is there a way to ask SQL to look for all reservation objects that are between two dates ?

You should use parameterized query with below logic:
"SELECT *
FROM RequestsQueueObjects
WHERE PODObjectID= #PODObjectID
and ((StartDateTime >= #StartDate and EndDateTime <= #EndDate)
OR (StartDateTime <= #StartDate and EndDateTime >= #StartDate)
OR (StartDateTime <= #EndDate and EndDateTime >= #EndDate)
OR (StartDateTime <= #StartDate and EndDateTime >= #EndDate))
";
Though above solution works, it can be simplified as below, thanks to link suggested by Thomas Haratyk.
http://logic-and-trick.com/Blog/The-Overlapping-Date-Range-Test
"SELECT *
FROM RequestsQueueObjects
WHERE PODObjectID= #PODObjectID
and EndDateTime >= #StartDate and StartDateTime <= #EndDate
";

EDIT
You want to check if the date ranges overlap. Try the following :
"SELECT *
FROM RequestsQueueObjects
WHERE PODObjectID='" +cPOD.PODObjectID + "'
and StartDateTime <= '" + EndDate+ "'
and EndDateTime >= '" + StartDate + "'";
( combine with Steve parameterized query recommendation )

Use a parameterized query and let the database engine figure out what is the date you pass.
In your code you write the dates between commas and this let the database engine to translate them according to its localization rules. Of course this could result in totally wrong results or in missing records
DateTime startDate = new DateTime(2015, 2, 1);
DateTime endDate = new DateTime(2015, 7, 1, 23, 59, 59); // add time to Include all day
string cmdText = #"SELECT * FROM RequestsQueueObjects
WHERE PODObjectID = #id
and StartDateTime >= #start
and StartDateTime <= #end";
using(SqlConnection cn = new SqlConnection(.....))
using(SqlCommand cmd = new SqlCommand(cmdText, cn))
{
cn.Open();
cmd.Parameters.Add("#id", cPOD.PODObjectID);
cmd.Parameters.Add("#start", StartDate);
cmd.Parameters.Add("#start", EndDate);
using(SqlDataReader reader = cmd.ExecuteReader())
{
....
}
}

Related

SQL Filter by dateTime

string query = "Select *From myTable where myTime>datetime('now','localtime','" + (-1 * day).ToString() + " days') ORDER BY myTime DESC";
day is a integer variable. If I set the day value to 1, database is filtering for 24 hours.
But if I set the day value to 1, I only want to see the logs of the new day.
How can I do that? Thank you for your help.
string query = "Select *From myTable where myTime>datetime('now','localtime','start of day', '" + (-1 * day).ToString() + " days') ORDER BY myTime DESC";

Data type mismatch criteria expression "Joining between 3 tables"

I have 3 tables: suppliers, bills, and payments. Each supplier has payments and bills. I want to retrieve a report like this one:
Supplier Name | total bills | total payments | balance
For a specific period that is specified by 2 DateTimePickers.
This my SQL query:
OleDbCommand cmd = new OleDbCommand("select c.sup_Name,c.sup_Place,sum(a.bill_Total),sum(d.pa_Value)
from (suppliers c left JOIN bills a
on c.sup_Id = a.bill_From)
left join payments d on c.sup_Id = d.pa_To
where (a.bill_Date >= '" + txbFrom.Text + "' and a.bill_Date <= '" + txbTo.Text + "') and (d.pa_EntryDate >= '" + txbFrom.Text + "' and d.pa_EntryDate <= '" + txbTo.Text + "')
group by c.sup_Name,c.sup_Place order by c.sup_Name asc", objConn);
OleDbDataReader dataReader = cmd.ExecuteReader();// Here the error appear.
For MySQL I had to convert the date: dt = DateTime which can easily be extracted from the DateTimePicker.
dt.ToString("yyyy-MM-dd H:mm:ss");
Don't format the parameters into an SQL string: instead use OleDbParameter to do this for you (and help avoid SQL injection attacks).
https://msdn.microsoft.com/en-us/library/system.data.oledb.oledbparameter(v=vs.110).aspx

select from table sql ce server between date returning 0

I am developing a windows form application in C#. I have a query where i want to select from date to date. the result is always 0.
My DB is a .sdf file, and in my table I have a datetime field to store the order date as DateTime.Now, and my PC dateformat is 10.12.2014,
Can any one please help me and explain why is this hapening..! Is there any better file format to save locally.? the application will be installed on several PC's, will the datetime format be a problem .? your help is much appricaitaed.. check please provide with some code.
internal static DataTable SearchItemsInOrders(string searchWord, string table, int minValue, int maxValue, out DataTable dtTable, DateTime dateFrom, DateTime dateTo)
{
string commandText = "select A.ItemName, B.Site, B.OrderId, A.Qty, B.Requester, B.Receiver, B.Date ";
commandText += "From tblOrderLine AS A Inner join tblOrder As B on A.OrderId=B.OrderId ";
commandText += "where A.ItemName='" + searchWord + "' and B.Date >= '" + dateFrom.ToShortDateString() + "' and B.Date <='" + dateTo.ToShortDateString() + "' Order By A.OrderId DESC";
SqlCeDataAdapter adp = new SqlCeDataAdapter();
SqlCeConnection con = ConAndData.Con;
dtTable = new DataTable();
adp = new SqlCeDataAdapter(commandText, con);
if (con.State == System.Data.ConnectionState.Closed)
{
con.Open();
}
adp.Fill(minValue, maxValue, dtTable);
return dtTable;
}
Try using this query,
string commandText = "select A.ItemName, B.Site, B.OrderId, A.Qty, B.Requester, B.Receiver, B.Date ";
commandText += "From tblOrderLine AS A Inner join tblOrder As B on A.OrderId=B.OrderId ";
commandText += "where A.ItemName='" + searchWord + "' and CONVERT(NVARCHAR(10),B.Date,121) >= CONVERT(NVARCHAR(10),'" + dateFrom.ToString("yyyy-MM-dd") + "',121) and CONVERT(NVARCHAR(10),B.Date,121) <= CONVERT(NVARCHAR(10),'" + dateTo.ToString("yyyy-MM-dd") + "',121) Order By A.OrderId DESC";
Hope this helps...
As it was suggested in comments - you have to use parameterized queries.
So, your commandText should be like:
string commandText = "select A.ItemName, B.Site, B.OrderId, A.Qty, B.Requester, B.Receiver, B.Date ";
commandText += "From tblOrderLine AS A Inner join tblOrder As B on A.OrderId=B.OrderId ";
commandText += "where A.ItemName=#ItemName and B.Date >= #DateFrom and B.Date <=#DateTo Order By A.OrderId DESC";
and later you should add parameters and values to the command:
adp = new SqlCeDataAdapter(commandText, con);
adp.SelectCommand.Parameters.Add("#ItemName", SqlDbType.NVarChar).Value = searchWord;
adp.SelectCommand.Parameters.Add("#DateFrom", SqlDbType.DateTime).Value = dateFrom;
adp.SelectCommand.Parameters.Add("#DateTo", SqlDbType.DateTime).Value = dateTo;
This also will prevent possible problems caused by incorrect date format produced by ToShortDateString().

How to find today's data from database from two different dates?

I have a database ShiftChange, and the fields are
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
I want to find today's shift from these table. I tried like this,
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();
}
Here connection is my connection class and query is my (sqldatareader dr) method.When I run this query I am getting shiftName 'MG' but actually the shiftName correspondent to today's date is 'AF' but it not getting. I hope it is my query's issue. Please show me the error
First of all you should make your query parameterized or you can prepare sql stored procedure and use that stored procedure in your code. I am giving you sql code for stored procedure here.
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
Btw, it's always better to use datatype date or datetime when dealing with dates.
I solved this issue with #Mukund's help. I applied his code in my project like this,
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();
}

how to view record within date range?

I have a records in my table Test like this my Date column is of type varchar.
Fname Lname Date
vivek parikh 01-09-2011 10:00:00 PM
kashyap vyas 02-09-2011 10:50:00 AM
viral panchal 02-09-2011 10:00:00 PM
Arpit Gosai 03-09-2011 10:00:00 PM
Darshit Chokshi 04-09-2011 10:00:00 PM
Sameer Rangrez 24-08-2011 9:15:12 AM
i want to fetch records within date range (start date and end date) from page.
my code is
DateTime time = DateTime.Today; // Use current time
string format = "MM-dd-yyyy";
SqlCommand cmd = new SqlCommand("select Fname,Lname,Insert_Date from Test where Insert_Date >= '" + Convert.ToDateTime(TextBox1.Text).ToString(format) + "' and Insert_Date <= '" + Convert.ToDateTime(TextBox2.Text).ToString(format) + "' ", con);
DataSet ds = new DataSet();
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(ds);
for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
{
Response.Write(ds.Tables[0].Rows[i]["Fname"].ToString());
Response.Write(ds.Tables[0].Rows[i]["Lname"].ToString());
Response.Write(ds.Tables[0].Rows[i]["Insert_Date"].ToString()+"<br>");
}
for building your query use Convert(datetime,fieldname,103) for converting varchar to datetime.
Your query should be something like.
select * from Test
where Convert(datetime,field_date,103) >= '2011-01-01' --start date
and Convert(datetime,field_date,103) <= '2012-01-01'; --end date
This is how your C# statement should look like (It should include 103 code to specify your date format which dd-mm-yyyy
SqlCommand cmd = new SqlCommand("select Fname,Lname,Insert_Date from Test where Convert(datetime,Insert_Date,103) >= '" + Convert.ToDateTime(TextBox1.Text).ToString(format) + "' and Convert(datetime,Insert_Date,103) <= '" + Convert.ToDateTime(TextBox2.Text).ToString(format) + "' ", con);
SELECT colname FROM tablename WHERE somecol >= '2011-01-09' AND somecol <= '2011-09-24'
select * from Test where Date >= '2011-09-02' and Date < '2011-0-04'
Check out the BETWEEN SQL operator. Also make sure you are formatting the dates correctly using the standard SQL Server format to avoid and potential confusion: yyyymmdd hhmmss, and remember to take the time portion of the date into account as well.
The following sql statement has been tested against our companys sql server 2008 and works fine.
SELECT *
FROM some_table
WHERE date_field >= '2011-10-25' and date_field <= '2011-11-26'

Categories