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();
}
Related
//I have this code and I want to insert only the date in the database without //the time, but this will always store value like this: 2019-10-19 00:00:00.000.
SqlCommand cmd2 = conn.CreateCommand();
cmd2.CommandType = CommandType.Text;
DateTime date = DateTime.ParseExact(TextBox_DepartureDate.Text, "dd/MM/yyyy", null);
DateTime date2 = DateTime.ParseExact(TextBox_ArrivalDate.Text, "dd/MM/yyyy", null);
string time1 = TextBox_DepartureTime.Text + " " + DropDownListAMPM.SelectedValue;
string time2 = TextBox_ArrivalTime.Text + " " + DropDownList_AMPM2.SelectedValue;
DateTime dateOnly1 = date.Date;
DateTime dateOnly2 = date2.Date;
if (date <= DateTime.Now.Date)
{
Label_EditTableMessage.ForeColor = System.Drawing.Color.Red;
Label_EditTableMessage.Text = "Departure Date Cannot be in the past";
}
else
{
if (date2 <= date)
{
Label_EditTableMessage.ForeColor = System.Drawing.Color.Red;
Label_EditTableMessage.Text = "Return Date Cannot be Less than the Departure Date";
}
else
{
cmd2.CommandText = "insert into flight(airline_id,flight_number,numer_seats,departure_city,destination_city,departure_time,arrival_time,departure_date,arrival_date) values( '" + DropDownList_AirlineId.SelectedValue + "','" + TextBox_FlightNumber.Text + "','" + TextBox_NumerSeats.Text + "', '" + TextBox_DepartureCity.Text + "', '" + TextBox_DestinationCity.Text + "', '" + time1 + "', '" + time2 + "', '" + dateOnly1 + "', '" + dateOnly2 + "') ";
cmd2.ExecuteNonQuery();
Label_EditTableMessage.ForeColor = System.Drawing.Color.Green;
Label_EditTableMessage.Text = "Flight Added";
EmptyTextBoxes();
GridView_Flight.DataBind();
}
}
}
The problem is not with your code. You should change the data type of your field in the database. Instead of datetime or datetime2 you should use date.
You can refer to this article: https://learn.microsoft.com/en-us/sql/t-sql/functions/date-and-time-data-types-and-functions-transact-sql?view=sql-server-ver15#DateandTimeRelatedTopics
2 parts to this:
Your schema probably has the column data type set to DATETIME instead of just DATE which is going to cause it to store the full date and time regardless. This is the first thing I would check.
In your C# you can use the .Date property on a DateTime object to get just the date part of it. This is irrelevant if you use the correct data type for your column as per point 1
date.Date
or if you want it in string format:
date.Date.ToShortDateString()
the problem is you use
DateTime dateOnly1 = date.Date;
DateTime dateOnly2 = date2.Date;
and previus you use
DateTime date = DateTime.ParseExact(TextBox_DepartureDate.Text, "dd/MM/yyyy", null);
DateTime date2 = DateTime.ParseExact(TextBox_ArrivalDate.Text, "dd/MM/yyyy", null);
you are working only with date, and the datetime assume the time with 00:00:00
try
{
conn5.Open();
OleDbCommand command = new OleDbCommand();
command.Connection = conn5;
string query = "select * from OrderDataListTable WHERE MONTH(`DATETIME`) = dateString";
command.CommandText = query;
reader = command.ExecuteReader();
What is the right syntax to compare my input month to the database?
String dateString = Convert.ToString(textBox2.Text);
DateTime month = Convert.ToDateTime(dateString + "01, 1990").Month;
You would use something like this with properly formatted string expressions for the dates of the interval:
DateTime monthDate = DateTime.Parse(textBox2.Text);
string startDate = new DateTime(monthDate.Year, monthDate.Month, 1).ToString("yyyy'/'MM'/'dd");
string endDate = new DateTime(monthDate.Year, monthDate.Month + 1, 1).AddDays(-1).ToString("yyyy'/'MM'/'dd");
and then:
string query = "select * from OrderDataListTable where [DATETIME] between #" + startDate + "# and #" + endDate + "#";
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())
{
....
}
}
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
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'