Advance search in LINQ - sql

How can i search in LINQ as stated below??
I Want to enter a string like this "a%b%c%d%" in my textbox and want result as we get in SQL.
Select *
from TableName
Where ColumnName Like 'a%b%c%d%'

LINQ doesn't have like operator, so you could first check if it contains a, b, c and d, then check if a is at start, b is before c, and c before d. Like this:
from item in context.TableName
where item.ColumnName.StartsWith("a") && item.ColumnName.IndexOf("b") != -1
&& item.ColumnName.IndexOf("c") != -1 && item.ColumnName.IndexOf("d") != -1
&& (
item.ColumnName.IndexOf("b") < item.ColumnName.IndexOf("c")
&& item.ColumnName.IndexOf("c") < item.ColumnName.IndexOf("d")
)
select item;

FROM item in context.TableName
WHERE item.ColumnName.StartWith("a%")
OR item.ColumnName.StartWith("b%")
OR item.ColumnName.StartWith("c%")
OR item.ColumnName.StartWith("d%")
SELECT item;

Related

how to get records from tempDB AX 2012 X++

I want to implement this functionality but vendBalanceProvisionalTmpProcesing is always empty, i know it is empty because it is tempDB :
while select AccountNum,PostingProfile from vendProvisionalBalanceTmpProcessing
{
select sum(AmountCur) from vendTrans
where vendTrans.AccountNum == vendProvisionalBalanceTmpProcessing.AccountNum
&& vendTrans.PostingProfile == vendProvisionalBalanceTmpProcessing.PostingProfile
&& vendTrans.TransDate >= _fromDate
&& vendTrans.TransDate <= toDate;
tempSum += vendTrans.AmountCur;
select sum(AmountMST) from vendTrans
where vendTrans.AccountNum == vendProvisionalBalanceTmpProcessing.AccountNum
&& vendTrans.PostingProfile == vendProvisionalBalanceTmpProcessing.PostingProfile
&& vendTrans.TransDate >= _fromDate
&& vendTrans.TransDate <=toDate;
tempSum+= vendTrans.AmountMST*ledgerParameters.EonExchangeRate;
tmpValue.Amount = tempSum;
tmpValue.AccountNum = vendTrans.AccountNum;
tmpValue.PostingProfile = vendTrans.PostingProfile;
tmpValue.doInsert();
}
But there are 2 scenarios where i can access to vendProvisionalBalanceTmpProcessing.AccountNum :
insert_recordset tmpValue
(AccountNum, PostingProfile, Amount)
select AccountNum
from vendProvisionalBalanceTmpProcessing
group by AccountNum
join PostingProfile, sum(AmountMST) from vendTrans
group by PostingProfile
where vendTrans.AccountNum == vendProvisionalBalanceTmpProcessing.AccountNum
&& vendTrans.PostingProfile == vendProvisionalBalanceTmpProcessing.PostingProfile
&& vendTrans.TransDate < _fromDate;
update_recordset vendProvisionalBalanceTmpProcessing
setting OpeningBalance = tmpValue.Amount
join tmpValue
where tmpValue.AccountNum == vendProvisionalBalanceTmpProcessing.AccountNum
&& tmpValue.PostingProfile == vendProvisionalBalanceTmpProcessing.PostingProfile;
Any way how i can do while select like that ?
`
I need vendProvisionalBalanceTmpProcessing.AccountNum to do two select sum over vendTrans where vendTrans.AccountNum == vendProvisionalBalanceTmpProcessing.AccountNum. So way how to do it similar to these two scenarios where i have access to vendProvisionalBalanceTmpProcessing would help me.
You would like to reread on how to link to a temporary table. Official documentation.
Especially, to access a tempDB table from outside where it is created, you need to call linkPhysicalTableInstance.

boolean algebra in SQL

I need to convert the following C statement to SQL query.
if((object->num1 == 10 && object->num2 == 11) || (object->num3 == 0 && object->num4 == 1)){
//something
}
I want something like
SELECT * FROM `table` WHERE (conditions here)
Thank you in advance.
You can use the following query:
SELECT *
FROM YOUR_TABLE
WHERE (num1=10 AND num2=11) OR (num3=0 AND num4=1);

SQL Server Stored Procedure Multiple Condtions

I have this LINQ in C#, which I have to convert to a SQL query. And I am not sure how to do multiple filtering based on conditions:
var geofenceReport = companyContext.GeofenceSimpleReports.Where(x => x.EnterTime != null && x.ExitTime != null && x.MinutesInGeofence != null).AsQueryable();
if (model.GeofenceId != -1)
{
geofenceReport = geofenceReport.Where(x => x.iGeofenceId == model.GeofenceId).AsQueryable();
}
if (model.AssetId != -1)
{
geofenceReport = geofenceReport.Where(x => x.iAssetId == model.AssetId).AsQueryable();
}
if (model.CategoryId != -1)
{
geofenceReport = geofenceReport.Where(x => x.iCategoryId == model.CategoryId).AsQueryable();
}
if (model.SiteId != -1)
{
geofenceReport = geofenceReport.Where(x => x.iSiteId == model.SiteId).AsQueryable();
}
geofenceReport = geofenceReport
.Where(x => x.EnterTime >= model.StartDateTime &&
x.EnterTime <= model.EndDateTime)
.AsQueryable();
So this is what I came up with in SQL:
I created a new type for AssetId:
USE myDatabase
GO
CREATE TYPE idTable AS TABLE (id INT)
And then in SQL:
USE myDatabase
GO
CREATE PROCEDURE [dbo].[xPT_GetGeofenceSummaryReport]
#iAssetIds idTable,
#iGeofenceId INT,
#iCategoryId INT,
#iSiteId INT,
#iAssetId INT
AS
IF #iAssetId != -1
SELECT * FROM GeofenceSimpleReport WHERE iAssetId in (#iAssetIds)
IF #iGeofenceId != -1
SELECT * FROM GeofenceSimpleReport where iGeofenceId = #iGeofenceId
IF #iCategoryId != -1
SELECT * FROM GeofenceSimpleReport where iCategoryId = #iCategoryId
IF #iSiteId != -1
SELECT * FROM GeofenceSimpleReport where iSiteId = #iSiteId
and this GeofenceSimpleReport is a database view.
But this will not work as it is logically wrong. This will 4 separate selects from the GeofenceSimpleReport.
I need to have one read from GeofenceSimpleReport with all filters applied.
And I don't want to read this data temporarily into a TABLE/LIST in memory as there is a lot of data.
Is there a way to write this query dynamically like I am doing in LINQ?
You're thinking about this procedurally, and going through a series of if-statements, rather than approaching your view as a set of data that you can filter all at once.
You can filter on the original criteria related to EntryTime, ExitTime, etc., and then for each parameter for which you provide a filterable value (not -1) then make sure the Id matches that record in the table. Anything where you gave a -1 for the value will automatically make that AND statement true.
I do this sort of thing all the time by passing in nullable parameters - if they're non-NULL then I filter on them - otherwise they just evaluate to true and pass through.
USE myDatabase
GO
CREATE PROCEDURE [dbo].[xPT_GetGeofenceSummaryReport]
#iAssetIds idTable,
#iGeofenceId INT,
#iCategoryId INT,
#iSiteId INT,
#iAssetId INT
AS
SELECT *
FROM GeofenceSimpleReport
WHERE EnterTime IS NOT NULL
AND ExitTime IS NOT NULL
AND MinutesInGeofence IS NOT NULL
AND (#iAssetId = -1 OR iAssetId IN (#iAssetIds))
AND (#iGeofenceId = -1 OR iGeofenceId = #iGeofenceId)
AND (#iCategoryId = -1 OR iCategoryId = #ICategoryId)
AND (#iSiteId = -1 OR iSiteId = #iSiteId)

Optional requirement on where clause in LINQ [duplicate]

This question already has answers here:
LINQ to SQL Where Clause Optional Criteria
(3 answers)
Closed 8 years ago.
The goal is to build a search form that can be entered on multiple field searches. But entering all fields are optional.
What is the equivalent code in LINQ?
Thanks.
string str = "";
if(a!="")
str += "f1 == a";
if(b!="")
str += " && f2 == b";
if(c!="")
str += " && f3 == c";
select f1, f2, f3 from p
where str;
You can build up the query sequentially in the same way, something like this:
var query = someData.Items;
if (a != string.Empty)
query = query.Where(x => x.f1 == a);
if (b != string.Empty)
query = query.Where(x => x.f2 == b);
…and so on. In the end, you have built a query with only the relevant predicates.
Try
from x in p where (x.f1 == a || a == "") && (x.f2 == b || b == "") && (x.f3 == c || c == "") select new { f1 = x.f1, f2 = x.f2, f3 = x.f3 }
The or on each search variable makes it ignored when empty string. I'm assuming you already took care of nulls in a, b, c.

Convert SQL - LINQ - Problem with using both Min/Max

Is there a online system which converts SQL - LINQ or can anyone else help convert the SQL - LINQ below?
SELECT MIN(startTime) As startTime, MAX(endTime) As endTime
FROM tblRA
LEFT JOIN tblA ON tblRA.asID = tblA.asID
WHERE 'xxxxxx' BETWEEN tblRA.startDate AND tblRA.endDate
AND tblA.availabilityDayOfWeek = 7
The main area I am having trouble is the .MAX/.MIN.
Heres what I have so far
public List<string> GetResourceAvailabilitiesByDate(DateTime searchDate)
{
DayOfWeek dayOfWeek = searchDate.DayOfWeek;
var minVal = from a in dc.tblResourceAvailabilities
join b in dc.tblAvailabilities on a.asID equals b.asID
where searchDate.Date >= a.startDate.Date && searchDate.Date <= a.endDate.Value.Date
&& b.availabilityDayOfWeek == (int)dayOfWeek
select b.startTime.ToShortTimeString();;
var maxVal = from a in dc.tblResourceAvailabilities
join b in dc.tblAvailabilities on a.asID equals b.asID
where searchDate.Date >= a.startDate.Date && searchDate.Date <= a.endDate.Value.Date
&& b.availabilityDayOfWeek == (int)dayOfWeek
select b.endTime.ToShortTimeString();
var min = minVal.Min(minVal.Min);
var max = maxVal.Max();
return min,max;
Thanks in advance for any help
Clare
I think your code is a little bit incorrect, and the first symptom of it is that you are using repeated code to define minval and maxval. I tried to simulate something similar to what you want and came to the following code, please adapt it to your needs.
public List<string> GetResourceAvailabilitiesByDate(DateTime searchDate)
{
DayOfWeek dayOfWeek = searchDate.DayOfWeek;
var vals = from a in dc.tblResourceAvailabilities
join b in dc.tblAvailabilities on a.asID equals b.asID
where searchDate.Date >= a.startDate.Date && searchDate.Date <= a.endDate.Value.Date
&& b.availabilityDayOfWeek == (int)dayOfWeek
select b;
var min = vals.Min(v => v.startTime).ToShortTimeString();
var max = vals.Max(v => v.startTime).ToShortTimeString();
return new List<string>() { min, max };
}
Some comments on your code, assuming it's C#.
You are trying to return an array of strings when you should be returning an array of dates.
Your where clause is pretty confuse. You're comparing the search date with startdate.Date and endDate.Value.Date. It does not make much sense.
Your select clause could select only b, or a, or whatever. You don't really need to select the date in it.