Compare date in specific format in LINQ - c#

i often compare date this way by in-line sql.
SELECT * FROM dbo.tbl_MyTable
WHERE
CONVERT(VARCHAR, DateTimeValueColumn, 112) >= CONVERT(VARCHAR, '20150101', 112) AND
CONVERT(VARCHAR, DateTimeValueColumn, 112) <= CONVERT(VARCHAR, '20150201', 112)
how could i instruct LINQ to generate the above SQL for date comparison. looking for sample code to achieve this. thanks

It would have been easier to answer if you actually told wanted to do: comparing only the dart part of timestamps. You convert them to format 112 (yyyyMMdd) in order to achieve that.
If you use LINQ queries you'll get DateTime objects for datetime or datetime2 columns. To compare the date part you can simply use the Date property of the DateTime objects, e.g.
[...]
where row.DateTimeColumn.Date >= new DateTime(2015, 1, 1) &&
row.DateTimeColumn.Date <= new DateTime(2015, 2, 1)

Related

C# sequence number issue in database

I have a column in the database table i.e. transaction Id. Its data type is var char(50). Now I want to save a row by combining the current date with a sequential number generated.
For Example 10/9/2016 is the date so first transaction is saved like 10920161 and the next one like 10920162 and so on. The sequential number is reset to 1 after every day.
How can I do this?
In SQL Server, it can be as simple as:
transactionId =
CONCAT(DATEPART(MONTH, GETDATE()),
DATEPART(DAY, GETDATE()),
DATEPART(YEAR, GETDATE()),
(SELECT COUNT(1)
FROM tableName
WHERE CONVERT(DATE, dateColumn) = CONVERT(DATE, getdate())) + 1)
Get the Number of transactions for that date, and add one to it. Concat that with a formatted string of Today's Date.
If you already have 3 records for today's date, the result would be:
100920164
Running SQL-Fiddle
Edit: EF suggested snippet:
string dateStr = DateTime.Today.ToString("Mdyyyy");
DateTime todayMidnight = DateTime.Today;
DateTime tomorrowMidnight = DateTime.Today.AddDays(1);
obj.transactionId = dateStr +
context.tableName.Count(x=> x.dateColumn >= todayMidnight
&& x.dateColumn < tomorrowMidnight) + 1;

Get data by month which has data type as nvarchar

I tried getting data by day, but not getting by month and year.
Need to retrieve data by month and year which has nvarchar datatype.
Select * from tbl_Details WHERE CONVERT(varchar(2), date, 101) = '02'
Edit:
The date is in the format of dd/mm/yyyy. The sample date is 24/02/2016
This is not the best solution, but one of the way to achieve your result.
First of all, Date is the reserved keyword, so don't use it, try with some other name.
If your date field is in the VARCHAR, you can check the condition by PARSENAME
SELECT * FROM #tbl_Details WHERE PARSENAME(REPLACE(SampleDate, '-', '.'), 2) = '02';
Sample execution for the same:
DECLARE #tbl_Details TABLE (SampleDate VARCHAR (20));
INSERT INTO #tbl_Details (SampleDate) VALUES
('2016-06-27'), ('2016-02-27'), ('2016-05-27'), ('2016-02-12');
SELECT *
FROM #tbl_Details
WHERE PARSENAME(REPLACE(SampleDate, '-', '.'), 2) = '02';
If the date format is stored in this format of 2016/02/27, in the replace function use '/' instead of '-' in the query above.
Update:
The OP has the date in the format of dd/mm/yyyy, so the below query worked in his case:
SELECT *
FROM #tbl_Details
WHERE PARSENAME(REPLACE(SampleDate, '/', '.'), 2) = '02'
AND PARSENAME(REPLACE(SampleDate, '/', '.'), 1) = '2016';
You need to convert to DATETIME first and then can use MONTH() function for that purpose like
select *
from tbl_Details
WHERE MONTH(CONVERT(Date, [date], 120)) = 2;
Select * from tbl_Details WHERE Month(cast(date as Date)) = 2
Or
Select * from tbl_Details WHERE Month(cast(date as Date)) = 2 and Year(cast(date as Date))=2016
Or
Select * from tbl_Details WHERE Format(cast(date as Date),'yyyy-MM') = '2016-02'

Week of year translation between c# and SQL

So I'm at the end of a long programming binge and I have one logical hurdle left to get over. My application presents KPIs for quote requests. The business leads have asked for these KPIs to be broken down by week, and I imagine when that is complete the request will come for a breakdown by month. I've figured this out in my SQL queries:
SELECT qpid FROM cpkpis WHERE DATEPART(ww, qpvalidfrom)=13 GROUP BY qpid;
Which will give my a list of qpids to compute a total from and provide actual primary keys for drill down.
What I can't get my head around is how to get an enumeration of weeks of the year form my C# code. I've looked the GregorianCalandar Class and specifically the GetWeekOfYear Method but I'm having trouble coming up with an enumeration of those values.
My question then is this: given a date range [lets say 2013-01-14 through 2013-04-10] how would I get an enumeration of the weeks of the year as ints between the start date and end date?
To help with with this task and the other requirements you're anticipating, you need a date table. IMHO the hardest thing to do in a database is to query data that isn't there.
You can query the date table:
Select Distinct DatePart(ww, dateField) as WeekNo
from DateTable
where dateField between '2013-01-14' and '2013-04-10';
From C#, an iterator is probably the simplest option:
public static IEnumerable<int> WeekNumbersBetween(
DateTime startDate,
DateTime endDate,
Calendar calendar = null,
CalendarWeekRule weekRule = CalendarWeekRule.FirstDay,
DayOfWeek firstDayOfWeek = DayOfWeek.Sunday)
{
if (calendar == null)
{
calendar = new GregorianCalendar();
}
DateTime week = startDate;
while (week <= endDate)
{
yield return calendar.GetWeekOfYear(week, weekRule, firstDayOfWeek);
week = week.AddDays(7);
}
}
The default values for the weekRule and firstDayOfWeek parameters should match the default settings in SQL. If your settings are different, you'll need to specify the correct values.
In T-SQL you could use something like:
DECLARE #StartDate DATE = '2013-01-14';
DECLARE #EndDate DATE = '2013-04-10';
WITH weekcte AS
(SELECT DATEADD(dd, -1, DATEADD(wk, DATEDIFF(wk, 0, #StartDate), 0)) AS DateValue
UNION ALL
SELECT DATEADD(wk, 1, DateValue)
FROM weekcte
WHERE DATEADD(wk, 1, DateValue) <= #EndDate )
SELECT DATEPART(ww, w.DateValue) AS 'Week No'
FROM weekcte AS w;

SQLite date comparison on non-valid Timestring formats

I want to get entries from a SQLite database by date.
SQLite valid timestring formats are listed here as:
YYYY-MM-DD
YYYY-MM-DD HH:MM
YYYY-MM-DD HH:MM:SS
YYYY-MM-DD HH:MM:SS.SSS
YYYY-MM-DDTHH:MM
YYYY-MM-DDTHH:MM:SS
YYYY-MM-DDTHH:MM:SS.SSS
HH:MM
HH:MM:SS
HH:MM:SS.SSS
now
DDDD.DDDD
I have another format in the database that is D/M/YYYY
Is there a way to compare dates in this database (and select entries accordingly) without having to select, parse and compare all the DateTime objects from all rows in the table?
you can compare dates in SQLITE by using some conventons
try to save dates in the same Format
SQLITE uses 3 Dateformats (not realy Formats but used ones)
* String as mentioned (YYYY-MM-DD [HH:MI:SS])
* Integer
* Real
I mostly use real for date-fields which are used for comparing
They have to be saved by the julianday() Function
The biggest Problem is, SQLITE has only a small date Converter function, so not well-formed dates can't or will not be correctly converted
Sqlite doesn't support comparing dates (and datetimes) specifically "out of the box".
As far as I know, you have three options (in order of my preference):
Use a format that is suited for string-based comparisons (e.g. YYYYMMDD). Here is something to get you started:
sqlite> create table foo (d TEXT);
sqlite> insert into foo values ('02/01/2012');
sqlite> select substr(d, 7, 4) || substr(d, 1, 2) || substr(d, 4, 2) from foo;
20120201
Use convoluted SQL to get it done using "out of the box" functions.
Create a function yourself.
I made a really FAST query and I am proud of it :p. So here it is:
public static string FromClausePartForDateComparisson(string tableName, string dateFieldName, string idFieldName, DateTime from, DateTime to)
{
string clause = string.Format(#" from
(SELECT {0} as filteredId,
Substr('00'|| -- make day with two digits
CASE Substr({1}.{2}, 3, 1)
WHEN '/' THEN Substr({1}.{2}, 1, 2)
ELSE Substr({1}.{2}, 1, 1)
END, -2, 2) AS DAY,
Substr('00'|| -- make month with two digits
CASE Length({1}.{2})
WHEN 8 THEN Substr({1}.{2}, 3, 1)
WHEN 9 THEN CASE Substr({1}.{2}, 3, 1)
WHEN '/' THEN Substr({1}.{2}, 4, 1)
ELSE Substr({1}.{2}, 3, 2)
END
WHEN 10 THEN Substr({1}.{2}, 4, 2)
END, -2, 2) AS MONTH,
Substr({1}.{2}, Length({1}.{2}) - 3, 4) AS YEAR
FROM {1}
WHERE Strftime('%Y%m%d', YEAR||'-'||MONTH||'-'|| DAY) BETWEEN
Strftime('%Y%m%d', '{3}') AND
Strftime('%Y%m%d', '{4}')) AS filteredtable
INNER JOIN {1} ON filteredtable.filteredId = {1}.{0} ", idFieldName, tableName, dateFieldName, from.ToString("yyyy-MM-dd"), to.ToString("yyyy-MM-dd"));
return clause;
}
And it is being used as:
var selectCommand = new SQLiteCommand("SELECT * " +
FromClausePartForDateComparisson("TABLENAME", "DATE", "ID", from, to) +
#"WHERE ID_TABLENAME=#Id";

SQL Server 2005, storing only date and checking the condition with date only

I am using SQL Server, and wants to store only the date part, if it stores the time also no issue, but while checking the condition, I want to consider only date.
for ex in .NET.
SELECT *
FROM checkins
WHERE checkindate='" + DateTime.Now.toShortDateString() + "'";
Use the CONVERT function to only get the date portion of the DateTime column:
SELECT *
FROM checkins
WHERE CONVERT(VARCHAR(10),checkindate, 106) ='" +
DateTime.Now.ToShortDateString() + "'";
Though, to make the date unambiguous I would not use ToShortDateString, but a custom format string:
DateTime.Now.ToString("d MMM yyyy")
So all together:
SELECT *
FROM checkins
WHERE CONVERT(VARCHAR(10),checkindate, 106) ='" +
DateTime.Now.ToString("d MMM yyyy") + "'";
SELECT *
FROM checkins
WHERE DATEADD(DAY, DATEDIFF(DAY, 0, checkindate), 0)
= DATEADD(DAY, DATEDIFF(DAY, 0, GETDATE()), 0)
SELECT dateadd(dd, datediff(dd,0,getdate()), 0)
will get you the date only while retaining it as a datetime type. Comparing datetime types tends to be more efficient than comparing strings.
That approach has the flexibility to ignore the day, month, get to the previous month, year, etc. See this article for more info.. http://www.sqlservercentral.com/articles/Date+Manipulation/69694/

Categories