Query Dates From SQLServer in C#? - c#

I am building a web application that is going to show the upcoming birthdays of a list of people stored in a SQL Server 2008 DB. I can't figure out how to query all records in the DB that are within 30 days of today's date.
Here's what I have so far:
using (HumanResourcesDB db = newH umanResourcesDB(ConfigurationManager.ConnectionStrings["HumanResourcesDB"].ConnectionString))
{
DateTime todaysDate = DateTime.Now;
List<Employee> record =
(from tab in db.Employees
where tab.Birthday between DateTime.Now and todaysDate.AddDays(30)
select tab).ToList();
this.grdBirthdays.DataSource = record;
this.grdBirthdays.DataBind();
}
of course the "between" and "and" don't work that's what I need filled in. I've searched the net for a little while to no avail. Any help?

Just use a greater than and less than
using (HumanResourcesDB db = newHumanResourcesDB(ConfigurationManager
.ConnectionStrings["HumanResourcesDB"].ConnectionString))
{
List<Employee> record = (from tab in db.Employees
where tab.Birthday >= DateTime.Today
&& tab.Birthday < DateTime.Today.AddDays(31)
select tab).ToList();
this.grdBirthdays.DataSource = record;
this.grdBirthdays.DataBind();
}
Also I should mention that I have used DateTime.Today rather than DateTime.Now because today represents the start of the day as 00:00:00.000. If someones birthday is set to whatever today is at 00:00:00.000 and you have used DateTime.Now (let's assume it's 8:00 in the morning). There birthday will not be included in this range because it is considered before "now".

Related

Entity Framework Getting current date rows(while time in that day)

I have table that the value of dateime is like this
2021-12-08 10:10:54.657
2021-12-08 10:10:41.567
2021-12-08 10:09:51.960
2021-12-08 10:10:54.657
2021-12-08 10:10:41.567
2021-12-08 10:09:51.960
2021-12-08 10:10:54.657
and I want to get that day or today (now is 8 dec 2021) . So i have tried using EF in controller :
ViewBag.CByUserToday = _db.ArrayDatas.Where(a => a.CreatedBy == user && a.CreatedDate == DateTime.Today.Date).Count();
But i still did not get the rows. When i tried to debug DateTime.Today.Date , it's said DateTime.Today = {09/12/2021 00:00:00} . But when i tried to update that createddate to '2021-12-09 00:00:00.000' it can be retrieved.
So, how to retrieve that rows that i have created today(ignoring the time) ?
Check that the column is greater than or equal to today, and less than tomorrow:
DateTime today = DateTime.Today;
DateTime tomorrow = today.AddDays(1);
ViewBag.CByUserToday = _db.ArrayDatas
.Where(a => a.CreatedBy == user
&& a.CreatedDate >= today
&& a.CreatedDate < tomorrow)
.Count();
That way, your DBMS will be able to use a suitable index on the CreatedBy and CreatedDate columns to satisfy your query.
It's usually preferable to avoid calling functions on a column when you're trying to filter it, since this means the query is not SARGable. However, according to this thread on DBA, casting a datetime/datetime2 column to date is SARGable, at least in Microsoft SQL Server.

one query with groupby / count / select new

I have to make in c# a query with linq to sql. I can handle it in sql but in linq to
sql is the result not what I wanted to get.
So there is a table with:
a day, in datetime with date and time
and a kind of id
I have to count the ids for each date, the time isn't important. So the result
should be something like:
day: 2013-11-12 amountIDs: 4
People said to me, I can make a select new query and in this query I can set the day
and could count the ids, or I make a group by day. I read similar question, but it doesn't work in my case.
Could somebody help me?
I tried it with the statement below, but the days have to be grouped, so now the output is foreach datetime, like this
day: 12.12.2013 12:00:00 amountIDs: 1
day: 12.12.2013 12:10:10 amountIDs: 1
In sql I made this statement:
SELECT CONVERT(VARCHAR(20), data.dayandtime, 106) AS day, count(data.amountIds) as ids
FROM data
WHERE ( data.dayandtime >= DATEADD(day, -28, getdate()) AND (data.type = 100) AND (data.isSomething = 0) )
GROUP BY CONVERT(VARCHAR(20), data.dayandtime, 106), data.isSomthing and it works.
I saw similar cases, where people made a : from-select-new xyz statement, than I made a view of it and tried to group just the view. Like this
var query = data.GroupBy(g => g.day.Value).ToList();
var qry = from data in dbContext
group data by data.day into dataGrpd
select new
{
day= dataGrpd.Key,
amountIDs= dataGrpd.Select(x => x.Id).Distinct().Count()
};
Check This

Check that a given date does not lie between two existing dates inside a datatable

I have one table which can store student leave start date and end date
like so:
StudentID Age startDate EndDate
1 14 5/05/2013 7/05/2013
4 17 4/04/2012 8/10/2012
I need to check to see if any new leave which is applied for doesn't fall in the range of leave already arranged for that student. For example, for the student with ID = 1, they should not be able to apply for leave which starts on 6/05/2013.
I'm using c# and am looking for a solution which uses SQL or LINQ.
normal SQL
Select count(*) from table where StudentID = 'parameterID' and startDate <= 'Parameter_StartDate' and EndDate <='Parameter_EnsDate';
DateTime dtApplied;
var allDates = yourDt.Rows.Cast<DataRow>().Where(x => dtApplied >= x.Field<DateTime>("startDate") && dtApplied <= x.Field<DateTime>("endDate"));
However I would consider using BETWEEN in SQL if I were you.
You can try this :
var result = dt.AsEnumerable().Where(r =>((int)r["StudentID"])==stdID &&
(DateTime)r["startDate"]<=yourStartDate &&
(DateTime)r["EndDate"]=YourEndDate))
.FirstOrDefault();
Or you can do this also:
string query="ID=1 AND startDate<=yourStratDate AND EndDate>=yourEndDate";
DataRow [] dr=dt.Select(strQuery);
select student_id From TableName Where Student_id = 1 and #dateToCheck not( between startdate and enddate)

SQL; Plus + or Minus – Instead of Dates (ASP.NET-C#)

I am Working On ASP.NET_C# Application
I am pulling out some Dates form SQL on a Grid View.
But instead of those Dates, I like to see how mush “Plus +” or “minus –“ It is form Today’s Date.
For Example
Today’s Date is = 11/02/2012
If the Date from SQL is 07/02/2012, I like my Grid to show -4
Or
If the Date from SQL is 17/02/2012, I like my Grid to show +6
Please Help me, How do I go about doing that….
This is My SQL Query; That I am working With
SELECT MAX(AmountPay.DateUpto) AS [ PaidUpTo], TimeTable.Name, TimeTable.Ref, TimeTable.Time11to12 FROM AmountPay FULL OUTER JOIN TimeTable ON AmountPay.Ref = TimeTable.Ref WHERE (TimeTable.Time11to12 = #Time11to12) GROUP BY TimeTable.Name, TimeTable.Ref, TimeTable.Time11to12
AmountPay.DateUpto is the Date I Like see as + or -
I have Been Suggested Datediff Function; and I have Used datediff function for working out things like Age from Date of Birth but I can't work out; how I can use this in the Case
Thanks in Advance
You can use Timespan
DateTime oldDate = DateTime.Now.AddDays(-4);
DateTime today = DateTime.Now;
TimeSpan span = oldDate.Subtract(today);
string diff = span.Days.ToString();
Since you are using MySQL, your select statement should be like:
SELECT DATEDIFF(CURDATE(), MAX(AmountPay.DateUpto)) AS [ PaidUpTo],
TimeTable.Name,
......
DATEDIFF will give you values like -1, 1, -5 ...and your DataGridView should display those values just fine.
SELECT DATEDIFF(day,GetDate(), MAX(AmountPay.DateUpto)) AS [ PaidUpTo], TimeTable.Name, TimeTable.Ref, TimeTable.Time11to12 FROM AmountPay FULL OUTER JOIN TimeTable ON AmountPay.Ref = TimeTable.Ref WHERE (TimeTable.Time11to12 = #Time11to12) GROUP BY TimeTable.Name, TimeTable.Ref, TimeTable.Time11to12

Query to return data from SQL Server table based on date criteria

I have the following piece of code in C# that I use to select some rows from a SQL Server table based on a date criteria.
DateTime From, DateTime To
SqlParameter[] oParam = new SqlParameter[3];
oParam[0] = new SqlParameter("#From", From.Date);
oParam[1] = new SqlParameter("#To", To.Date);
DataTable dt = clsDatabaseHistory.ExecuteReader("SELECT * FROM tblHistory WHERE Date_Requested BETWEEN #From and #To", oParam);
If for example From=18/08/2011 and To=18/08/2011 and there is data in the table tblHistory that has the Date_Requested value as 18/08/2011 the query does not return it.
But if I change the value of To from 18/08/2011 to To=19/08/2011 the query returns me all the values from the table that have a Date_Requested value of 18/08/2011, but none from the 19/08/2011.
How can something like that be possible and what query should I use to return rows where the date field is between date1 and date2.
Something like :
select * rows where datevalue >= date1 and datevalue <= date2
Thank you.
Change your query to use >= and <
select * rows where datevalue >= date1 and datevalue < date2 + 1
I bet your Date_Requested in your table also has some time associated with it - so it probably really is 18/08/2011 14:37 or something like that.
The BETWEEN clause will be selecting anything between 18/08/2011 00:00:00 and 18/08/2011 00:00:00 - basically nothing.
What you need to take into account when working with DATETIME is the fact there's always also TIME involved!
If you want everything for today, you need to use:
BETWEEN `18/08/2011 00:00:00` AND `18/08/2011 23:59:59`
With those two values, you should get all rows with a Date_Requested of today.
OR: in SQL Server 2008 and newer, you could also use the DATE column type which stores date only - no time portion involved. In that case, you should be fine with your query values.
From.Date and To.Date gets the date portion on c# side ignoring the time portion; you need to do something similar on the database side.
Try
"SELECT * FROM tblHistory WHERE cast(Date_Requested as DATE) BETWEEN #From and #To"
to remove the time portion.
EDIT:
as explained in this answer, you could change #To param value to
oParam[1] = new SqlParameter("#To", To.Date.AddDays(1));
You need to account for time (not just date). One way I handle that is like this:
SELECT
...
WHERE CONVERT(varchar(8), date_begin, 112) <= convert(varchar(8), #to, 112)
This converts dates to YYYYMMDD format (with no time), which is very easy to use in <, >, = comparrisons.
Ok, thanks to you all, i've done the following thing
oParam[2] = new SqlParameter("#To", To.Date.AddDays(1));
and used the following select
SELECT * from MyTable WHERE CONVERT(varchar(8), Date_Requested, 112) >= CONVERT(varchar(8), #From, 112) and CONVERT(varchar(8), Date_Requested, 112) < CONVERT(varchar(8), #To, 112)
Datetime variables must be converted to be compared.
Thanks all!

Categories

Resources