how to view record within date range? - c#

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'

Related

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

How to provide dates in a culture-agnostic way to MS Access OleDb Command?

I'm working on a C# program. In that program, I select some dates from Access 2010 database and process data. But, I can't access and process data on rows containing dates from a range of 01/12/2014 and 11/12/2014 but I can process remaining dates.
cmd = new OleDbCommand("SELECT MIN([Vch No]) FROM [" + group + "] WHERE [Entry Date]=#" + date + "#", conn);
long Vch = long.Parse(cmd.ExecuteScalar().ToString()) - 1;
I get error on line long Vch = ... - 1; saying can't get proper Input string. Whereas, it works for other dates either before or after these particular dates.
I declare the date by this code :
cmd = new OleDbCommand("SELECT TOP 1 * FROM (SELECT DISTINCT [Entry Date] FROM [" + group + "]) WHERE [Entry Date]>#" + initDate + "# ORDER BY [Entry Date]", conn);
dr = cmd.ExecuteReader(); dr.Read();
string date = dr["Entry Date"].ToString();
Thank you in advance!
Try setting you date variable to a non culture specific date format, so YYYY/MM/DD e.g. 2014/12/01
If date is a C# DateTime object, you'll need to call:
date.ToString("yyyy/MM/dd", CultureInfo.InvariantCulture);
As per convert datetime to yyyy/MM/dd
So:
cmd = new OleDbCommand("SELECT MIN([Vch No]) FROM [" + group + "] WHERE [Entry Date]=#" +
date.ToString("yyyy/MM/dd", CultureInfo.InvariantCulture) +
"#", conn);
long Vch = long.Parse(cmd.ExecuteScalar().ToString()) - 1;
EDIT TO ADD
As per #Gord-Thompson's comment, it's always considered best practise to use parameters where ever possible (generally always!).
So:
cmd = new OleDbCommand("SELECT MIN([Vch No]) FROM [#pGroup] WHERE [Entry Date]=#pDate", conn);
cmd.Parameters.Add("#pGroup", OleDbType.NVarChar).Value = group;
cmd.Parameters.Add("#pDate", OleDbType.DateTime).Value = date;
long Vch = long.Parse(cmd.ExecuteScalar().ToString()) - 1;
Try to avoid using cmd.Parameters.AddWithValue() - see http://blogs.msmvps.com/jcoehoorn/blog/2014/05/12/can-we-stop-using-addwithvalue-already/ for more details.

SQL Query for simple reservation system

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())
{
....
}
}

C# Mysql select Date(yyyy/mm/dd) from column by month value (12)

I am trying to figure out the way to sum values of certain columns. How do I get Date month value from Date column where all values are in date (yyyy/mm/dd) format?
What I should write in :
WHERE Data = '"?????"' ";
I want to pick up date where month equals 12.
Here is my code :
MySqlConnection cnn = new MySqlConnection(connectionString);
cnn.Open();
string query = "select sum(SUMA) from `nuolatines pajamos` WHERE ID = '" + perdavimo1.id_permetejas.ToString() + "' WHERE Data = '"+ now.Month +"' ";
MySqlCommand createCommand = new MySqlCommand(query, cnn);
var sum = createCommand.ExecuteScalar().ToString();
nl_pajamos.Text = sum.ToString();
DateTime.Parse(stringobject,cultureinfo);
for example
DateTime.Parse("20-01-2014",new CultureInfo("nl-BE

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();
}

Categories