DATEDIFF (in months) in linq - linq

select col1,col2,col3 from table1
where(DATEDIFF(mm, tblAccount.[State Change Date], GETDATE()) <= 4
I want to convert this sql query to LINQ. but I dont know any DateDiff alternative in LINQ. can you please suggest me?

You're looking for SqlMethods.DateDiffMonth.
EDIT: In EF4, use SqlFunctions.DateDiff.

Putting aside your original question for a moment, in your query you use:
where(DATEDIFF(mm, tblAccount.[State Change Date], GETDATE()) <= 4
This query would always cause a full table scan, since you're comparing the result of a function call against a constant. It would be much better if you calculate your date first, then compare your column value against the calculated value, which would allow SQL to use an index to find the results instead of having to evaluate every record in your table.
It looks like you're trying to retrieve anything within the past 4 months, so in your application code, try calculating the date that you can compare against first, and pass that value into your Linq2Entities expression:
DateTime earliestDate = new DateTime(DateTime.Now.Year, DateTime.Now.Month, 1).AddMonths(-4);
var results = from t in context.table1
where t.col3 >= earliestDate
select t;

In EF6, the class to use is DbFunctions. See, for example, DbFunctions.DiffMonths.

I solved this problem in another manner: I calculated the date from code:
theDate = Date.Now.AddMonths(-4)
And in EF change the condition:
tblAccount.[State Change Date] < theDate

Related

Re-write to_char function

When I use to_char function, It's know as internal_function in EP, and Index can't work in this column. Are there any way to re-write it? I don't want to create a function based index
This is my predicates code.
TO_CHAR(createdate,'dd-mm-yyyy') = TO_CHAR(systimestamp,'dd-mm-yyyy')
Many thanks.
Yes, this is exactly the reason we must use purely the date column on one side and a trunc(sysdate) like expression on the other instead of TO_CHAR while doing date comparisions.
where createdate >= trunc(sysdate)
and createdate < trunc(sysdate) + 1

Compare date to month-year in Postgres/Ruby

I have a date column in my table and I would like to 'filter'/select out items after a certain year-month. So if I have data from 2010 on, I have a user input that specifies '2011-10' as the 'earliest date' they want to see data from.
My current SQL looks like this:
select round(sum(amount), 2) as amount,
date_part('month', date) as month
from receipts join items
on receipts.item = items.item
where items.expense = ?
and date_part('year', date)>=2014
and funding = 'General'
group by items.expense, month, items.order
order by items.order desc;
In the second part of the 'where', instead of doing year >= 2014, I want to do something like to_char(date, 'YY-MMMM') >= ? as another parameter and then pass in '2011-10'. However, when I do this:
costsSql = "select round(sum(amount), 2) as amount,
to_char(date, 'YY-MMMM') as year_month
from receipts join items
on receipts.item = items.item
where items.expense = ?
and year_month >= ?
and funding = 'General'
group by items.expense, year_month, items.order
order by items.order desc"
and call that with my two params, I get a postgres error: PG::UndefinedColumn: ERROR: column "year_month" does not exist.
Edit: I converted my YYYY-MM string into a date and passed that in as my param instead and it's working. But I still don't understand why I get the 'column does not exist' error after I created that column in the select clause - can someone explain? Can columns created like that not be used in where clauses?
This error: column "year_month" does not exist happens because year_month is an alias defined the SELECT-list and such aliases can't be refered to in the WHERE clause.
This is based on the fact that the SELECT-list is evaluated after the WHERE clause, see for example: Column alias in where clause? for an explanation from PG developers.
Some databases allow it nonetheless, others don't, and PostgreSQL doesn't. It's one of the many portability hazards between SQL engines.
In the case of the query shown in the question, you don't even need the to_char in the WHERE clause anyway, because as mentioned in the first comment, a direct comparison with a date is simpler and more efficient too.
When a query has a complex expression in the SELECT-list and repeating it in the WHERE clause looks wrong, sometimes it might be refactored to move the expression into a sub-select or a WITH clause at the beginning of the query.

Oracle - Another way for month query?

first... sorry for my english.
I have a query like this:
Select *
From tableA
Where (
TO_NUMBER(TO_CHAR(dateA(+),'SYYYY')) = 2013
AND TO_NUMBER(TO_CHAR(dateA(+),'MM')) = 02
AND to_number(to_char(dateA(+),'dd')) <= 25
)
and retrieve me the data from each date until last number that I give as parameter, in this case the day 25. This working but delay very much because the form of "Where" statement... anybody know another way that retrieve the data so fast and with the same functionality?
It sounds like you want
SELECT *
FROM tableA
WHERE dateA BETWEEN trunc( date '2013-02-26', 'MM' ) AND date '2013-02-26'
This will return all the rows where dateA is between the first of the month and the specified date. If there is an index on dateA, Oracle would be able to use it for this sort of query (though whether it actually would is a separate issue).

Dynamic order by date data type in Oracle using CASE

My code in the stored procedure:
SELECT * FROM
my_table ir
WHERE
--where clause goes here
ORDER BY
CASE WHEN p_order_by_field='Id' AND p_sort_order='ASC' THEN IR.ID end,
CASE WHEN p_order_by_field='Id' AND p_sort_order='DESC' THEN IR.ID end DESC,
CASE WHEN p_order_by_field='Date' AND p_sort_order='ASC' THEN TO_CHAR(IR.IDATE, 'MM/dd/yyyy') end,
CASE WHEN p_order_by_field='Date' AND p_sort_order='DESC' THEN TO_CHAR(IR.IDATE, 'MM/dd/yyyy') end DESC;
Problem is that sorting is done based on the char, which comes out wrong for the date case. CASE statement, however, won't allow any other datatype other than char. So what is the solution in this case? I need to be able to pass the p_order_by_field into the stored procedure.
Thanks
Should be simple - just use ISO date format in your case:
TO_CHAR(IR.IDATE, 'yyyy-mm-dd')
and you should be fine.
Another problem could occure when you want to sort on the date difference (let say number of days between two days).
For example such a sort would return number 13 (days) before 9 (days).
The solution is that you concatenate length of date difference and the difference itself:
length(trunc(date2) - trunc(date1)) || to_char(date2 - date1)

Oracle date function

I am executing the below query,It returns me the blank row.However there are records in the table having upd_time = '12-MAR-08'.I don't understand why it is not returning the date '12-MAR-08'.Please help me out??
SELECT br_data.upd_time FROM BANKREC.br_data
where br_data.upd_time = '12-MAR-08';
It's likely that upd_time isn't exactly 12-MAR-08. The date format is not showing the time component, but it's probably there (DATE data type in Oracle can contain both date and time components).
Try this (it will allow you to see the time components):
alter session set nls_date_format='DD-MON-YY HH24:MI:SS';
SELECT br_data.upd_time FROM BANKREC.br_data
where br_data.upd_time >= to_date('12-MAR-08','DD-MON-YY')
and br_data.upd_time < to_date('13-MAR-08','DD-MON-YY');
Is it the same if you do a
SELECT br_data.upd_time FROM BANKREC.br_data
where trunc(br_data.upd_time) = '12-MAR-08';
It could be that the upd_time is not a date, but a timestamp, so it actually contains for instance '12-MAR-08 05:30' which wouldn't be the same thing. trunc() removes the time part of the timestamp.
Since it doesn't return an error, I assume that it parses the date correctly, but otherwise you could try with to_date('12-MAR-08','DD-MON-YY')
You should use Oracle's function to convert your string properly into a date using
to_date('12-MAR-08', 'DD-MMM-YY')
Then you have to take into account that the Oracle "Date" datatype also contains time information to the nearest second. This means that the date that was constructed in the first step is actually midnight on March 12th. So you have to make sure that the upd_time is truncated to midnight:
trunc(upd_time, 'DAY') = to_date('12-MAR-08', 'DD-MMM-YY')
Your full query becomes
SELECT br_data.upd_time
FROM BANKREC.br_data
WHERE trunc(upd_time, 'DAY') = to_date('12-MAR-08', 'DD-MMM-YY');
There are other ways to skin this cat (you could transfer your updTime column to a proper char field with to_char(upd_time, 'DD-MMM-YY')), but it's usually advisable make the data you are looking for similar to what you can find in the database as that increases your chances of using an index for the lookup.
i don't have access to an oracle db at the moment but i remember using to_char.
try
SELECT br_data.upd_time FROM BANKREC.br_data where to_char(br_data.upd_time, 'DD-MON-YY') = '12-MAR-08';

Resources