I have A problem with dividing the value of 0 by 0 in an Access database - vb.net

When I try to extract the result of Division 2 Field from table in access database
If I have a value of 0 an error occurs
sqlSTR = "SELECT TBL_Category_Item_File.Item_Org_Price2/TBL_Stocks_Balances.Item_QTY AS ['Price']FROM (((TBL_Category_Item_File INNER JOIN TBL_Suppliers_Product ON TBL_Category_Item_File.Item_ID = TBL_Suppliers_Product.Item_ID) INNER JOIN TBL_Suppliers ON TBL_Suppliers_Product.Supp_ID = TBL_Suppliers.Supp_ID) INNER JOIN TBL_Sub_categories ON TBL_Category_Item_File.ID_Sub_categories = TBL_Sub_categories.ID_Sub_categories) INNER JOIN TBL_Stocks_Balances ON (TBL_Stocks_Balances.Item_ID = TBL_Category_Item_File.Item_ID) AND (TBL_Category_Item_File.Item_BarCode = TBL_Stocks_Balances.Item_Barcode) WHERE tbl_Category_Item_File.Catg_ID =" & Split(cmblist.Text, " - ")(0)

If you are trying to avoid the error, you can use a CASE statement in your query to check for a 0 value in the Item_Org_Price2 field and return a different value if it is 0. For example, you could do something like this:
SELECT
CASE
WHEN TBL_Category_Item_File.Item_Org_Price2 = 0
THEN 0
ELSE TBL_Category_Item_File.Item_Org_Price2/TBL_Stocks_Balances.Item_QTY
END AS ['Price']
FROM (((TBL_Category_Item_File INNER JOIN TBL_Suppliers_Product ON TBL_Category_Item_File.Item_ID = TBL_Suppliers_Product.Item_ID) INNER JOIN TBL_Suppliers ON TBL_Suppliers_Product.Supp_ID = TBL_Suppliers.Supp_ID) INNER JOIN TBL_Sub_categories ON TBL_Category_Item_File.ID_Sub_categories = TBL_Sub_categories.ID_Sub_categories) INNER JOIN TBL_Stocks_Balances ON (TBL_Stocks_Balances.Item_ID = TBL_Category_Item_File.Item_ID) AND (TBL_Category_Item_File.Item_BarCode = TBL_Stocks_Balances.Item_Barcode) WHERE tbl_Category_Item_File.Catg_ID =" & Split(cmblist.Text, " - ")(0)

Related

Convert SQL Query to LINQ query/Lambda expression

I am trying to fetch the results from the DB using the Entity Framework using the below SQL query:
SELECT
Header_Id,
Header_Number, Details_Id,
Details_Header_Date,
(SELECT TOP 1 c.[Comment_Description] FROM [Comment] c
WHERE c.[Comment_CarrierId] = i.[Header_CarrierId] AND c.[Comment_ParentEntityId] = i.[Header_Id]
ORDER BY c.Comment_AddedOn DESC) AS 'HeaderComments',
CONCAT(ht.[HeaderTracker_Reason], ' ', ht.[HeaderTracker_Notes]) AS 'RejectedComments',
at.[InternalComments] AS 'InternalComments',
CASE i.[Header_Status]
WHEN 'Pending' THEN ar.[HeaderTracker_ApprovedLvl] END AS 'ApprovedLevel',
CASE i.[Header_Status]
WHEN 'Pending' THEN ar.[HeaderTracker_DueBy] END AS 'ApprovedDueDate'
FROM [Header] i
LEFT OUTER JOIN [Details] ii
ON i.[Header_Id] = ii.[Details_HeaderId]
INNER JOIN [Carrier] t
ON t.[Carrier_Id] = i.[Header_CarrierId]
LEFT OUTER JOIN [HeaderTracker] ht
ON ht.[HeaderTracker_HeaderId] = i.[Header_Id] AND ht.[HeaderTracker_Type] = 'Rejected'
LEFT OUTER JOIN [AdjustmentTracker] at
ON at.[DetailsId] = ii.[Details_Id]
LEFT OUTER JOIN [HeaderTracker] ar
ON ar.[HeaderTracker_HeaderId] = i.[Header_Id]
AND i.[Header_Status] IN ('Paid', 'Pending', 'Approved', 'PaidWithAdj')
AND ar.[HeaderTracker_IsPending] = 1
The result output should be using LINQ query / LAMBDA expression
The following code is what I tried: (not sure how TOP 1 and CASE would come here + if & is also valid here)
var statuses = new string[] { "Paid", "Pending", "Approved", "PaidWithAdj" };
var hdrdet =
(
from hdr in dbContext.Headers
join det in dbContext.Details on hdr.Header_Id equals det.Header_Id into hdrdet
from h in hdrdet.DefaultIfEmpty()
join carr in dbContext.Carriers on hdr.Carrier_Id equals carr.Header_Carrier_Id into carrs
from c in carrs.DefaultIfEmpty()
join hdrtk in dbContext.HeaderTracker on hdr.Header_Id equals hdrtk.HeaderTracker_HeaderId && hdrtk.HeaderTracker_Type equals "Rejected" into hdrtks
from k in hdrtks.DefaultIfEmpty()
join adjt in dbContext.AdjustmentTracker on adjt.DetailsId equals det.Details_Id into adjts
from a in adjts.DefaultIfEmpty()
join pnd in dbContext.HeaderTracker on pnd.HeaderTracker_HeaderId equals hdr.Header_Id && hdr.Header_Status contains(statuses) && pnd.[HeaderTracker_IsPending] equals 1 into pnds
from p in pnds.DefaultIfEmpty()
select new
{
hdrid = Header_Id,
hdrnumber = Header_Number, Details_Id,
det_date = Details_Header_Date,
reason = HeaderTracker_Reason + ' ' + HeaderTracker_Notes,
intcomments = InternalComments
}
)

How to avoid union all

Any possibility methods to avoiding "Union all" when different joining > conditions varies on each section
SELECT RS1.*, EXL.*
FROM "EXL" "EXL"
INNER JOIN "RS1" "RS1"
ON "RS1"."HEADER_KEY" = "EXL"."HEADER_KEY"
WHERE "RS1"."PIPE_KEY" = '1109' AND
"RS1"."COLK" IS NULL AND
"RS1".CT1 = 0 AND "RS1".CT2 > 0
UNION ALL
SELECT RS1.*, EXL.*
FROM "EXL" "EXL"
INNER JOIN "RS1" "RS1"
ON "RS1"."HEADER_KEY" = "EXL"."HEADER_KEY"
INNER JOIN "YFS"."STATUS_MAP" "SOS"
ON "SOS"."STATUS" = "RS1"."STATUS"
INNER JOIN "RS1" "RS2"
ON "RS2"."LINE_KEY" = "RS1"."CHAINLINE_KEY" AND
"RS2"."PIPEKEY" = "SOS"."TYPE_KEY" AND
"RS2"."STATUS" = "SOS"."EXTN_STATUS" AND
"RS2"."PIPE_KEY" = '4093'
WHERE "RS1"."PIPE_KEY" = '1109' AND
"RS1"."COLK" IS NULL AND
"RS1".CT1 = 0 AND "RS1".CT2 > 0
Since the two SELECTs have exactly the same WHERE-condition, I assume that you want to return rows from EXL, even when rows from YFS.STATUS_MAP are missing (otherwise please explain what your intention is). You can do this with LEFT JOIN
SELECT RS1.*, EXL.*
FROM
"EXL"
INNER JOIN "RS1"
ON "RS1"."HEADER_KEY" = "EXL"."HEADER_KEY"
LEFT JOIN "YFS"."STATUS_MAP" "SOS"
ON "SOS"."STATUS" = "RS1"."STATUS"
LEFT JOIN "RS1" "RS2"
ON "RS2"."LINE_KEY" = "RS1"."CHAIN_LINE_KEY" AND
"RS2"."PIPEKEY" = "SOS"."TYPE_KEY" AND
"RS2"."STATUS" = "SOS"."EXTN_STATUS" AND
"RS2"."PIPELINE_KEY" = '4093'
WHERE "RS1"."PIPELINE_KEY" = '1109' AND
"RS1"."COLK" IS NULL AND
"RS1".CT1 = 0 AND "RS1".CT2 > 0

Convert to linq sql query error

I have a query according to the :
SELECT
tblDefinition.TopsisType, tblTemplate.tType, tblEvaluationFormCategory.Title AS EvaluationCategory,
CASE tType WHEN 1 THEN N'2'
ELSE N'1' END ProcessType,
tblDefinition.Description, tblDefinition.TemplateID, 1 Destinition
FROM tblTemplate INNER JOIN
tblEvaluationFormCategory ON tblTemplate.CategoryID = tblEvaluationFormCategory.ID INNER JOIN
tblEFQMAlternative INNER JOIN
tblDefinition ON ([tblEFQMAlternative].[TopsisID] = [tblDefinition].[TopsisID] AND [tblEFQMAlternative].[CustomerID] = [tblDefinition].[CustomerID]) INNER JOIN
tblGroupMembers ON ([tblDefinition].[TopsisID] = [tblGroupMembers].[TopsisID]
AND tblDefinition.CustomerID =
tblGroupMembers.CustomerID) ON tblTemplate.TemplateID = tblDefinition.TemplateID
INNER JOIN
tblTerm ON tblDefinition.TermGrant = tblTerm.Title
WHERE (tblTerm.ID = 20) AND (tblGroupMembers.UserID = 558)
GROUP BY tblDefinition.TopsisType, tblTemplate.tType, tblEvaluationFormCategory.Title,
tblDefinition.Description, tblDefinition.TemplateID
when i convert to linq, then error to :
Field [([tblDefinition].[TopsisID] = [tblGroupMembers]].[[TopsisID] AND tblDefinition.CustomerID = tblGroupMembers.CustomerID) ON tblTemplate.TemplateID] not found in the current Data Context.
What should I do?

Access 2003 SQL Syntax error

I am new with access 2003 and been stuck on this query I have wrote for a while now. The tables and column names, operators and brackets i believe are all correct however I am getting a syntax error only after I inserted the following join operation
FROM (tDailyEntries
INNER JOIN tLEDGERS ON tLEDGERS.Action = tDailyEntries.ActionNo)
INNER JOIN (tProjects
below is my full code
SELECT DISTINCT tProjects.CC_IO AS ProjectNo,
Year([DateFrom]) & " Accrual " & MonthName(Month([DateFrom])) & " - "+[CompanyName] & " ( "+([LastName]) & ")" AS [Line/Item/Text],
tUsers.LastName AS Last_Name,
tDailyEntries.UserId AS UserID,
contractordailyrate AS DailyRate,
contractordailyhours AS Hours,
ROUND(contractordailyrate / contractordailyhours, 2) AS HourlyRate,
ROUND(SUM(tDailyEntries.CalculatedDailyHours), 2) AS MonthlyHours,
ROUND((HourlyRate * MonthlyHours), 2) AS Charge,
ROUND(Charge+ROUND((Charge*0.2),2),2) AS Accruals, tProjects.Project AS Project
FROM (tDailyEntries
INNER JOIN tLEDGERS ON tLEDGERS.Action = tDailyEntries.ActionNo)
INNER JOIN (tProjects
RIGHT JOIN (textcontractor
RIGHT JOIN (tTitle
RIGHT JOIN ((Location
RIGHT JOIN (tDepartments
RIGHT JOIN tUsers
ON tProjectType.ProjectTypeID = tProjects.ProjectTypeID)
ON tDepartments.DeptID = tUsers.DeptID)
ON tLocation.LocationID = tUsers.LocationID)
RIGHT JOIN (((tDailyEntries
LEFT JOIN tDepartments AS tDepartments_1
ON tDailyEntries.DeptCharged = tDepartments_1.DeptShortName)
LEFT JOIN tActions ON tDailyEntries.ActionNo = tActions.ActionID)
LEFT JOIN tLookups
ON tDailyEntries.Zone = tLookups.LookupID)
ON tUsers.UserID = tDailyEntries.UserID)
LEFT JOIN textmain
ON tUsers.UserID = textmain.userID)
ON tTitle.TitleID = tUsers.TitleID)
ON textcontractor.companyid = textmain.contractorcompany)
ON tProjects.ProjectID = tDailyEntries.ProjectNo
WHERE tTitle.TitleID = 37
AND Month([DateFrom]) = MonthNum
AND Day([DateFrom]) <21
GROUP BY tProjects.CC_IO, Year([DateFrom]) & " Accrual " & MonthName(Month([DateFrom])) & " - "+[CompanyName] & " ( "+([LastName]) & ")", tUsers.LastName, tDailyEntries.UserId, textmain.contractordailyrate,
Month([DateFrom]), textmain.contractordailyhours, tProjects.Project;
Any help would be great.

Left Join Linq to Entity's Vb.net

I can't figure out that linq to entity query syntax. My problem is that if the value of the Calls table is null then noting comes up, I want to make something like a left join to get 'all' rows from the Calls table.
I tried to group it but I can't figure out the correct way to write it.
Dim TicketQuery As ObjectQuery = From c In EnData.Customer _
Join t In EnData.Calls On t.CustomerID Equals c.CustomerID _
Join Status In EnData.Lists On t.Status Equals Status.ListValue _
Join Project In EnData.Lists On t.Project Equals Project.ListValue _
Join Priorty In EnData.Lists On t.Priority Equals Priorty.ListValue _
Where c.Status > -1 And t.Status > -1 And Status.ListType = 1 And Project.ListType = 3 And Priorty.ListType = 2 _
Select New With {c.CustName, t.CallID, t.CallDate, t.CallTime, t.Description, Key .Status = Status.ListText, Key .Project = Project.ListText, t.DateModified, Key .Priority = Priorty.ListText}
How can I fix that?
Similar question: Linq to Sql: Multiple left outer joins
Microsoft Documentation: http://msdn.microsoft.com/en-us/library/bb918093.aspx#Y916
LINQ Examples from: http://msdn.microsoft.com/en-us/vbasic/bb737909
Left Outer Join
A so-called outer join can be expressed with a group join. A left outer joinis like a cross join, except that all the left hand side elements get included at least once, even if they don't match any right hand side elements. Note how Vegetables shows up in the output even though it has no matching products.
Public Sub Linq105()
Dim categories() = {"Beverages", "Condiments", "Vegetables", "Dairy Products", "Seafood"}
Dim productList = GetProductList()
Dim query = From c In categories _
Group Join p In productList On c Equals p.Category Into Group _
From p In Group.DefaultIfEmpty() _
Select Category = c, ProductName = If(p Is Nothing, "(No products)", p.ProductName)
For Each v In query
Console.WriteLine(v.ProductName + ": " + v.Category)
Next
End Sub
For left join in VB.net we can use Let
Dim q =
(From item In _userProfileRepository.Table
Let Country = (From p In _countryRepository.Table Where p.CountryId = item.CurrentLocationCountry Select p.Name).FirstOrDefault
Let State = (From p In _stateRepository.Table Where p.CountryId = item.CurrentLocationCountry Select p.Name).FirstOrDefault
Let City = (From p In _stateRepository.Table Where p.CountryId = item.CurrentLocationCountry Select p.Name).FirstOrDefault
Where item.UserId = item.ProfileId.ToString)
After the left join we can use group by
Dim q2 =
(From p In q Group p By p.Country, p.State, p.City Into Group
Select New With
{
.Country = Country,
.State = State,
.City = City,
.Count = Group.Count
}).ToList()