Search data only day value of date - c#

Is it possible to search a data by day or month value of a date type value in mysql and c#.net.please can any one help me?

You can use DAY and MONTH functions:
SELECT *
FROM yourtable
WHERE DAY(date_column) = 1
or
SELECT *
FROM yourtable
WHERE MONTH(date_column) = 1
have a look at MySQL date and time functions.

Related

SQL query to extract number of dates in the same month

I want to write a SQL command that selects from database the number of rows in which the date has the same year and month as this year and month.
For example: it's July 2020 now, so I want the command to extract the no. of rows in which the dates lie in July 2020.
From what I have understood on the other answers from Stackoverflow, I wrote this C# code:
cmd = new SqlCommand("SELECT COUNT(date) FROM ordertbl WHERE MONTH(date) = MONTH(GETDATE()) AND YEAR(date) = YEAR(GETDATE())", con);
dr = cmd.ExecuteReader();
dr.Read();
lblthismonth.Text = dr[0].ToString();
dr.Close();
The column with the date is called date.
It would be better not to manipulate your table data. Search a calculated range instead:
SELECT COUNT(date)
FROM ordertbl
WHERE
date >= CAST(DATEADD(DAY, 1, EOMONTH(GETDATE(),-1)) AS DATE) and
date < CAST(DATEADD(DAY, 1, EOMONTH(GETDATE())) AS DATE)
With your query, if you have a million rows, and 100,000 of them match, sqlserver must do 2 million date operations to extract the year and month from the million dates, and then 2 million comparisons comparing the extracted numbers. An index can not be used
If you work out a date range, and the column is indexed, then sqlserver can use the indexed data because it isn't being manipulated, and know which 100,000 rows to retrieve. In the case of a Count like this it doesn't even need to hit the table; it can just count the index
Typically we should always try to avoid putting a function call on the left hand side of a comparison operator in a WHERE clause

Update 2 million rows for 1 column

I have a table with approximately 2 million records. I have to loop through each record and update the effective date. I need to set the day to the first of the month for each date.
If the current date is the first of the month, then ignore.
i.e.
07/01/2018
07/21/2018 => 07/01/2018
08/11/2018 => 08/01/2018
Currently, I'm writing this as a C# program and it taking way too long.
Is there a better solution?
Just use DATEADD() and DATEDIFF() combination to get the first of the month date
UPDATE t
SET datecol = DATEADD(MONTH, DATEDIFF(MONTH, '1900-01-01', datecol), '1900-01-01')
FROM yourtable t;
It could be as simple as:
Update myTable
set myDate = DateAdd(day, 1-Day(myDate), myDate)
where day(myDate) > 1;

Using sql to add to dates during a query

I have a table that keeps track of when particular events occur, and how long they last. For reasons I cannot fathom, it was designed to store the start date of the event, start time of the event, then the number of hours and minutes the event lasted. Like this:
EventStartDate | EventStartTime | TimeSpentHours | TimeSpentMinutes
Where EventStartDate is a dateTime with the hours/minutes always set to zero, so that, even though it's a date time, all the values are like "12/22/2016 00:00". The EventStartTime is a char(4) which is military time of the start of the event. TimeSpentHours is and int which is the total hours the event duration, and TimeSpentMinutes is an int for the number of minutes. Obviously the total time spent for the event is the hours plus the minutes.
The problem: I need to be able to, given a particular DateTime, find all the events that were occuring during that time. Put another way, given a particular DateTime I need to get all the events with a starting date and time that's greater than or equal to the given DateTime and less than or equal to an "end" date and time.
So I need to compute the "EndDateTime" based off the values in the database during the query. The database is SqlServer 2008 R2. I am using C# for WinForm application to query the data.
So far I have roughly:
public static List<ImportantEvents> GetEventsDuringDateTime(DateTime timeOfEvent)
{
using (SqlConnection sqlConn = getAndOpenSqlConn())
{
string theEventTime = timeOfEvent.ToString("hhmm");
string sqlStmt = "SELECT EVENT_ID, AGENCY, EVENTSTARTDATE, ACTNOTE, EVENTSTARTTIME, TIMESPENTHOURS, TIMESPENTMINUTES FROM EVENTSMAIN WHERE((EVENTSTARTDATE<= #MYEVENTDATETIME AND EVENTSTART TIME< #ACTTIME) AND ...";"
}
}
(the above SQL obviously won't work and is where I am stuck...)
My question is: how can I, in the query, add the EVENTSTARTTIME to the EVENTSTARTDATE to create a new "temporary" column, then add the TIMESPENTHOURS and TIMESPENTMINUTES to that column into another new "temporary" column, to then query against given a specific DateTime value???
It is possible to achieve this in a single query with a common-table expression like this:
With StartAndEndTimes As (
Select Event_ID,
EventStart = DateAdd(Minute, Convert(int, Right(EventStartTime, 2)), DateAdd(Hour, Convert(int, Left(EventStartTime, 2)), EventStartDate)),
EventEnd = DateAdd(Minute, Convert(int, Right(EventStartTime, 2))+TimeSpentMinutes, DateAdd(Hour, Convert(int, Left(EventStartTime, 2))+TimeSpentHours, EventStartDate))
From EventsMain)
Select Event_Id, EventStart, EventEnd, <<add other fields here>>
From StartAndEndTimes
Where EventStart <= #MyEventDateTime
And EventEnd > #MyEventDateTime;
Basically you can extract the hours and minutes from the start time and add them to the start date to get a true, datetime, start date. Similar with the end date. It is not necessary to use common-table expression here, but it does make the code more readable. Then you just do the ordinary date comparison to your input parameter.
Here I have disected parts of the final query. You will need to put the final part into your query wherever you need it.
SELECT Combined = EVENTSTARTDATE + EVENTSTARTTIMEFROM FROM EventsMain
SELECT CombinedWithHour = DATEADD(hh, TIMESPENTHOURS, Combined) FROM EventsMain
SELECT CombinedWithMinute = DATEADD(mi, TIMESPENTMINUTES, CombinedWithHour) FROM EventsMain
All together:
SELECT DATEADD(mi, TIMESPENTMINUTES, DATEADD(hh, TIMESPENTHOURS, EVENTSTARTDATE + EVENTSTARTTIME)) FROM EventsMain

Query to display +- 2 days of data but return only selected date itself

I would like to send a MySQL query where I choose a date from my C# programming comboBox e.g. 04/06/2014. Then result should show +-2days including 04/06/2014 itself. i.e. result will ended up showing data from 02/06/2014 till 06/06/2014 (a total of 5 days) in my dataGridView. My MySQL command below shows only the data for 04/06/2014, can someone kindly correct my code? Any help would be much appreciated!
Note: Assuming the 04/06/2014 will be replaced by my C# code comboBox_stockDates.SelectedItem.ToString()
SELECT Prices_Date, Prices_Time, Prices_Open
FROM tableprices
WHERE Ticker_ID = 732
AND DATE_ADD(STR_TO_DATE('04/06/2014', '%d/%m/%Y'), INTERVAL - 2 DAY)
AND DATE_ADD(STR_TO_DATE('04/06/2014', '%d/%m/%Y'), INTERVAL - 1 DAY)
AND Prices_Date = STR_TO_DATE('04/06/2014', '%d/%m/%Y')
AND DATE_ADD(STR_TO_DATE('04/06/2014', '%d/%m/%Y'), INTERVAL + 1 DAY)
AND DATE_ADD(STR_TO_DATE('04/06/2014', '%d/%m/%Y'), INTERVAL + 2 DAY)
ORDER BY Prices_Date ASC, Prices_Time ASC;
Your SELECT filters only the column Price_Date and current date. This one should work for you:
SELECT Prices_Date,
Prices_Time,
Prices_Open
FROM tableprices
WHERE Ticker_ID = 732
AND Prices_Date >= DATE_ADD (STR_TO_DATE ('04/06/2014', '%d/%m/%Y'), INTERVAL -2 DAY)
AND Prices_Date <= DATE_ADD (STR_TO_DATE ('04/06/2014', '%d/%m/%Y'), INTERVAL +2 DAY)
ORDER BY Prices_Date ASC, Prices_Time ASC;
For using the indexes of your table effectively (if there are any) it's better to convert the dates before the query as Chris suggested.
Any reason you can't do the conversion in C#? Seems cleaner.
Then it'd be a select from table where date greater than or equal and date less than or equal.
C# Code:
var dt = DateTime.ParseExact(comboBox_stockDates.SelectedItem.ToString(), "dd/MM/yyyy", System.Globalization.CultureInfo.InvariantCulture);
var start = dt.AddDays(-2);
var end = dt.AddDays(2);
Then select:
SELECT prices_date,
prices_time,
prices_open
FROM tableprices
WHERE ticker_id = 732
AND ( prices_date >= [startdate]
AND prices_date <= [enddate] )
ORDER BY prices_date ASC,
prices_time ASC;
Will this not work for you?

Month/Year SQL to correct format

I have a textfield that users input the date using a modified jquery datepicker. The textfield has the Month and Year such as 'July 2011'
I need to run a query to search for results between July 1, 2011 and July 31, 2011. My date in the database is a smalldatetime, so I need my query to look like this:
select * from members where signupdate between 'july 1 2011' and 'july 31 2011'
How can I get the user inputted date of July 2011 converted to 'July 1 2011' and 'July 31 2011'?
EDIT
I'm only getting a 0 value from InvalidCount but I know I have one record in there as a test. Why isn't it being counted?
MY PROC:
SELECT
(SELECT COUNT(*) FROM dbo.Members m WHERE m.memberID = #pMemberID AND m.SignUpDate BETWEEN #pDate AND DATEADD(MONTH, 1, #pDate)-1) AS 'SignUpDate',
COALESCE(SUM(m.ValidCount), 0) AS ValidCount,
COALESCE(SUM(m.InvalidCount), 0) AS InvalidCount
FROM
dbo.Members m
INNER JOIN
dbo.MemberStats ms ON m.MemberID = ms.MemberID
WHERE
m.SignUpdate BETWEEN #pDate AND DATEADD(MONTH, 1, #pDate)-1
The exact syntax depends on the SQL Engine, but if you start with the 1st of the month, then add 1 month, and finally subtract 1 day; you get the end of the month.
(I'll assume MS SQL Server to match your C# tag)
SELECT
*
FROM
members
WHERE
signupdate BETWEEN #param AND DATEADD(MONTH, 1, #param) - 1
If the between isn't required, you can use DatePart.
Untested example:
where DATEPART(yyyy, SignupDate) = 2011 and DATEPART(m, SignupDate) = 7
convert varchar to appropiate format you want and then compare
check the list of formats. Hope this helps dude.
convert date
Firstly, you must convert the string representation to a valid DateTime struct object on the server. You can use var date = DateTime.ParseExact("july 1 2011", "MMMM dd yyyy", CultureInfo.CurrentUICulture) or DateTime.TryParse. Then you pass this into your SqlCommand as parameters. Never use strings when querying, especially when it comes from user input.

Categories

Resources