So, right now my code has something like this:
if(DateA <= utcNow || (DateA == null && DateB <= utcNow)) doSomething();
I want to do something like this now:
if(!InitialExpression) continue;
AFAIK, if A || B, the negation would be !A && !B.
But this doesn't work: if(DateA > utcNow && (DateA != null || DateB > utcNow)) continue;.
When DateA = null and DateB > utcNow it should fall into the continue but it doesn't.
Edit:
My mistake was assuming the opposite of DateA <= utcNow is DateA > utcNow. But it's DateA == null || DateA > utcNow
Option 1 - use an ELSE statement
if(DateA <= utcNow || (DateA == null && DateB <= utcNow))
{doSomething()
}else{
dpSomethingElse();
Option 2 - use ! in the operator
if(!(DateA <= utcNow || (DateA == null && DateB <= utcNow))) doSomethingElse();
Option 3 - negation - The condition of DataA not being null will need to go first. There is some context missing but assuming you want to negate the expression by ensuring that give preference to DateA if it is greater than utcNow, else check for DateB being greater then utcNow
if((DateA != null && DateA > utcNow) || DateB > utcNow) doSomethingElse()
The opposite of DateA <= utcNow || (DateA == null && DateB <= utcNow) is
(DateA == null || DateA > utcNow) && (DateA != null || DateB == null || DateB > utcNow)
Your logic was pretty much alright #Felipe. Just that you overlooked a tiny aspect.
The negation of <= is not just > but it also includes a NULL value.just add these 2 conditionals along with an OR operator. This should work.
Check the updated statement below:
(DateA == null || DateA > utcNow) && (DateA != null || DateB == null || DateB > utcNow)
Related
IF inputVariable = '0'
THEN
DELETE existingTemptable
WHERE status != 999;
ELSE
IF inputVariable = '1'
THEN
DELETE existingTemptable
WHERE status = 999;
ELSE
DELETE existingTemptable
WHERE status != 999
AND date < utils.dateadd('MONTH', -6, SYSTIMESTAMP);
END IF;
END IF;
This If logic is present on a temp table and I have to remove the temp table and make it only select query , so approached with WITH CTE but stuck in the below
what should be in the where clause
with existingTemptable as
(
//got the temp table here
), myTable as
(
Select * from existingTemptable
**where
status = CASE WHEN inputVariable = '0' THEN 999
WHEN inputVariable != '0' AND inputVariable != '1' THEN 999
ELSE status
END**
)Select * from myTable
What to put in WHERE clause so that it mimics the If logic above
You have to be careful if inputVariable or status (or both) may be null. The rest is a direct application of logical rules one learns (or should learn) in middle school.
select *
from existingTemptable
where inputVariable = '0' and (status = 999 or status is null)
or
inputVariable = '1' and (status != 999 or status is null)
or
(inputVariable is null or inputVariable not in ('0', '1'))
and (status = 999 or status is null) and date >= [whatever]
Note - even in the absence of null handling, you can't write the where clause with a case expression; that's because in one branch you require "not equal", and you can't do it with a simple case expression.
Not all filtering in where contions. The first pass to check if items are active or discontinued evaluates then the second portion of the were evaluates to check what type of item. The last portion of the where checking for quantity values is not evaluating and with variables passed.
query:
from i in items
join idt in itemDetails on i.Id equals idt.ItemId
join ip in itemPrice on i.Id equals ip.ItemId
join s in supplier on i.SupplierID equals s.Id
join so in salesOrderItems on i.Id equals so.ItemId into salesTable
from x in salesTable.DefaultIfEmpty()
where (i.ItemStatus == "ACT" || i.ItemStatus == "DISC" && i.StoreID == null)
&& (i.ItemType == stock || i.ItemType == part || i.ItemType == specialOrder)
&& (idt.ReorderQty >= sales || idt.WarrantyQty >= warranty || idt.NextOrderQty >= next || idt.ReorderPoint > reorderPoint || x.SalesOrderItemStatus == requests)
Attempting to subtract two dates from one another to figure out the number of days, then execute .Average() on the 'let' variable avgConversion.
I encounter the following error; LINQ to Entities does not recognize the method 'System.TimeSpan Subtract(System.DateTime)' method, and this method cannot be translated into a store expression.
var averageConversion =
(
from r in db.Registrations
where
(bu == "All" || r.BusinessUnit.Equals(bu)) &&
(region == "All" || r.Region.Equals(region)) &&
(startDate == null || r.StartDate >= startDate) &&
(endDate == null || r.EndDate <= endDate) &&
!r.RegistrationStatus.Equals("Cancelled") &&
!r.Status.Equals("Cancelled")
let avgConversion = r.StartDate.Value.Subtract(r.RegistrationDate.Value).Days
select avgConversion
).Average();
Thanks to Enigma, this is what ended up solving the problem.
var dates = (from r in db.Registrations
where
(bu == "All" || r.BusinessUnit.Equals(bu)) &&
(region == "All" || r.Region.Equals(region)) &&
(startDate == null || r.StartDate >= startDate) &&
(endDate == null || r.EndDate <= endDate) &&
!r.RegistrationStatus.Equals("Cancelled") &&
!r.Status.Equals("Cancelled")
select new
{
r.RegistrationDate,
r.StartDate
}).ToList();
var avgConversion = (from d in dates
let AvgConversion = d.StartDate.Value.Subtract(d.RegistrationDate.Value).Days
select AvgConversion).Average();
Remember that Entity Framework translates a subset of all possible LINQ statements into SQL. If you use methods or functions that can't be translated the you get the "method cannot be translated into a store expression" error.
Instead you should pull your data into memory before doing the calculation so that you can run the full LINQ expression.
Like this:
var averageConversion =
(
from r in db.Registrations
where
(bu == "All" || r.BusinessUnit.Equals(bu)) &&
(region == "All" || r.Region.Equals(region)) &&
(startDate == null || r.StartDate >= startDate) &&
(endDate == null || r.EndDate <= endDate) &&
!r.RegistrationStatus.Equals("Cancelled") &&
!r.Status.Equals("Cancelled")
select new
{
r.StartDate,
r.RegistrationDate
}
)
.ToArray()
.Select(r => r.StartDate.Value.Subtract(r.RegistrationDate.Value).Days)
.Average();
I always thought LINQ to SQL equivalent for an exists query is to use Any(). But i recently wrote a query in LINQ , which basically is trying to find if duplicate records exists in single table.
Anycontext.Contacts.Any(c => ((c.FirstName == contact.FirstName && c.LastName == contact.LastName && c.AddressLine1 == contact.AddressLine1 && c.Zip == contact.Zip)||
(!String.IsNullOrEmpty(contact.Email) && c.Email == contact.Email)))
matching criteria is simple to find contacts with same FirstName, LastName and AddressLine1 or same Email. This query times out in 30 sec(default), there are just 500K rows in this table.
Wherecontext.Contacts.Where(c => ((c.FirstName == contact.FirstName && c.LastName == contact.LastName && c.AddressLine1 == contact.AddressLine1 && c.Zip == contact.Zip)||
(!String.IsNullOrEmpty(contact.Email) && c.Email == contact.Email))).Count()>0
I was forced to use Where clause and then do count greater than 0 to find if any duplicate exists in the set. What i can not understand is, why LINQ to SQL on simple Any clause timing out.
Any explanation will be really great here.
EDIT
SQL From from LINQ Pad
ANY
SELECT
(CASE
WHEN EXISTS(
SELECT NULL AS [EMPTY]
FROM [Accounts].[Contacts] AS [t0]
WHERE ([t0].[CompanyID] = #p0) AND ((([t0].[FirstName] = #p1) AND ([t0].[LastName] = #p2) AND ([t0].[AddressLine1] = #p3) AND ([t0].[Zip] = #p4)) OR (([t0].[FirstName] = #p5) AND ([t0].[LastName] = #p6) AND (EXISTS(
SELECT NULL AS [EMPTY]
FROM [Accounts].[PhoneNumbers] AS [t1]
WHERE ([t1].[ContactNumber] = #p7) AND ([t1].[ContactID] = [t0].[ContactID])
))))
) THEN 1
ELSE 0
END) AS [value]
Where
SELECT [t0].[ContactID]
,[t0].[CompanyID]
,[t0].[CompanyTitle]
,[t0].[FirstName]
,[t0].[LastName]
,[t0].[AddressLine1]
,[t0].[AddressLine2]
,[t0].[City]
,[t0].[State]
,[t0].[Zip]
,[t0].[Email]
,[t0].[Salutation]
,[t0].[IsActive]
FROM [Accounts].[Contacts] AS [t0]
WHERE ([t0].[CompanyID] = #p0)
AND (
(
([t0].[FirstName] = #p1)
AND ([t0].[LastName] = #p2)
AND ([t0].[AddressLine1] = #p3)
AND ([t0].[Zip] = #p4)
)
OR (
([t0].[FirstName] = #p5)
AND ([t0].[LastName] = #p6)
AND (
EXISTS (
SELECT NULL AS [EMPTY]
FROM [Accounts].[PhoneNumbers] AS [t1]
WHERE ([t1].[ContactNumber] = #p7)
AND ([t1].[ContactID] = [t0].[ContactID])
)
)
)
)
Not completely sure if this is what you want, but you could compare, I'm guessing you wont run the test often, as it would be better to test for existence before you input the data to the DB.
If you want to find the duplicates then
var queryA = from a in db.someTable
select a.value;
foreach(var row in queryA){
Console.Write(queryA.Where(b => b == row).Count() > 1 ? row: "");
}
If you just want to test if it exist then.
var queryA = from a in db.someTable
select a.value;
var queryB = queryA;
queryB.Distinct();
Console.Write(queryB.Count() != queryA.Count() ? "Yes" : "No");
I have the following SQL statement:
CASE
WHEN wt.pmtlr_oi IS NULL OR (SELECT COUNT(*) FROM mc.SCHEDENTRY WITH (NOLOCK) WHERE wt_oi = wt.wtskoi AND shedref_oi NOT IN (SELECT shdoi FROM mc.SCHDULE WITH (NOLOCK) WHERE aenm LIKE '%Breakin%')) = 0 AND wt.pmtlr_oi IS NULL
THEN 'Break-In'
ELSE 'Planned'
END AS schedule
which I have translated into:
Schedule = wt.pmtlr_oi == null || (from sch in SCHEDENTRies where wt_oi == wt.wtskoi && shedref_oi !(from sc in SCHDULEs
where sc.Aenm.Contains("Breakin") select sc.Shdoi)).Count() == 0 && wt.pmtlr_oi == null ? "Break-In" : "Planned"}
Here's how it looks in the select statement:
select new {Schedule = wt.pmtlr_oi == null || (from sch in SCHEDENTRies where wt_oi == wt.wtskoi && shedref_oi !(from sc in SCHDULEs
where sc.Aenm.Contains("Breakin") select sc.Shdoi)).Count() == 0 && wt.pmtlr_oi == null ? "Break-In" : "Planned"});
However when I try and run it there are some problems which I do not know how to fix. The first one is that the compiler doesn't appear to like the NOT IN found here:
&& shedref_oi !(from sc in SCHDULEs
I get a "A query body must end with a select clause or a group clause" error.
The compiler also doesn't like this:
select sc.Shdoi)).Count() == 0
On the outer parenthesis I get a "Syntax error ',' expected" error and on the period I get a "Statement expected" error message.
I would appreciate some help in troubleshooting this.
EDIT:
OK, After the comments I have corrected the LINQ statement to look like this:
select new {Schedule = wt.pmtlr_oi == null || (from sch in SCHEDENTRies where wt_oi == wt.wtskoi && !(from sc in SCHDULEs
where sc.Aenm.Contains("Breakin") select sc.Shdoi).Contains(shedref_oi)).Count() == 0 && wt.pmtlr_oi == null ? "Break-In" : "Planned"});
and the compiler likes it. However, it still doesn't like the .Count(). I get a "Statement expected" error. Am I incorrect in using .Count() for the sql SELECT COUNT(*)?