how to convert child - parent sql query to linq or lambda expression - linq

i have tsql query. it is work fine. i want to convert it to linq query or lambda expression
DECLARE #myHID BIGINT;
SET #myHID = 1;
WITH tblChild AS
(
SELECT *
FROM wbs.WBS w WHERE w.ParentId = #myHID
UNION ALL
SELECT w2.* FROM wbs.WBS w2 JOIN tblChild ON w2.ParentId =
tblChild.hID
)
SELECT
tblChild.hID, Unit.ID, w3.wbsName + ' * ' + tblChild.wbsName,
tblChild.FK_WbsBaseStructure_hID, tblChild.parentID, unitNumber,
unitTitle, FK_UsageItem_ID, usageTitle, nominalArea
FROM tblChild
inner join unit.Unit on tblChild.hID = Unit.FK_WBS_hID
inner join unit.UsageItem on Unit.FK_UsageItem_ID = UsageItem.ID
left join wbs.WBS w3 on tblChild.parentID = w3.hID
thank's

I didn't notice you are using a recursive CTE in your SQL. Unfortunately, there is no good direct translation of a recursive CTE. The recommended approach is to create a Stored Procedure or View based on the recursive SQL and access that.
For translating SQL to LINQ,
Translate subselects as separate variables
Translate each clause in LINQ clause order, leaving monadic operators (DISTINCT, TOP, etc) as functions applied to the whole LINQ query.
Use table aliases as range variables. Use column aliases as anonymous type field names.
Use anonymous types (new { }) for multiple columns
Left Join is simulated by using a join variable and doing another from from the join variable followed by .DefaultIfEmpty().
Replace coalesce with the conditional operator and a null test.
Use Concat for UNION ALL and Union for UNION.

Related

Oracle function perform better than inline query

I have one long query which have a lot of let join with subqueries. It 's have some performance issue. I have just put subqueries inside new function and the function execute that subqueries and store the output in a collection (user defined table which contain user defined object). when I execute outer query with this function it's perform better than subqueries but we don't found the answer why it's happend.
Example : Existing Query
select *
from a
left join (select * from b left join c on b.something =c.something where b.something=`something`) d on a.something = d.something
Update the query
create object user_obj as ( column_name varchar, column_name varchar);
create or replace TYPE table_name AS TABLE OF user_obj;
create function test (something) as
report table_name := table_name();
Begin
for i in (select * from b left join c on b.something =c.something where
b.something='something')loop
report.EXTEND;
report(report.count) := (user_obj(i.firstcolumnvalue,
i.secondColumnValue))
end loop;
return report;
End
calling function by outer query
select * from a left join (select * from table(test(input_data))) d on a.something = d.something
When I executing through function it's give me better performance as compare to inline query
I want a reason why performance is better in function

how to compare one value against 2 values in Oracle

I want to compare a a value against 2 values without using OR or DECODE. The value I want to compare with two values is the one which I am getting as a return code of a function. If I use OR or DECODE then I have to call function twice and it gives performance hit. Currently I am coding as below
select *
from table1 t1, table2 t1
where t1.empid = t2.empid
and myfunction(t2.balance) = t1.total OR myfunction(t2.balance) = -1
Please suggest if there is a way to call function once and compare with 2 values.
To shorten your code you could use IN operator which acts like OR.
select *
from table1 t1
join table2 t1 on
t1.empid = t2.empid
and myfunction(t2.balance) in (t1.total, -1)
I've also replaced old-fashioned join syntax in where clause for JOIN keyword and you're advised to be using that in your future SQL journeys.
Good thing to know would be that even though you call the function twice, most modern databases would actually call it only once, so I wouldn't be that much concerned about it.

How to convert my TSQL query to LINQ

I am new to linq. I can't convert this SQL code to linq. Please help me. Thanks.
DECLARE #myHID BIGINT;
SET #myHID = 1;
WITH tblChild AS
(
SELECT *
FROM wbs.WBS w
WHERE w.ParentId = #myHID
UNION ALL
SELECT w2.*
FROM wbs.WBS w2
JOIN tblChild ON w2.ParentId = tblChild.hID
)
SELECT
tblChild.hID ,
Unit.ID, w3.wbsName + ' * ' + tblChild.wbsName as
structure ,
tblChild.FK_WbsBaseStructure_hID ,
tblChild.parentID ,
unitNumber ,
unitTitle ,
FK_UsageItem_ID,
usageTitle ,
nominalArea
FROM
tblChild
INNER JOIN
unit.Unit ON tblChild.hID = Unit.FK_WBS_hID
INNER JOIN
unit.UsageItem ON Unit.FK_UsageItem_ID = UsageItem.ID
LEFT JOIN
wbs.WBS w3 ON tblChild.parentID = w3.hID
Please convert this to linq code.
Thanks.
For translating SQL to LINQ query comprehension:
Translate FROM subselects as separately declared variables.
Translate each clause in LINQ clause order, leaving monadic operators (DISTINCT, TOP, etc) as functions applied to the whole LINQ query.
Use table aliases as range variables. Use column aliases as anonymous type field names.
Use anonymous types (new { }) for multiple columns
Left Join is simulated by using a into join_variable and doing another from from the join variable followed by .DefaultIfEmpty().
Replace COALESCE with the conditional operator and a null test.
SELECT * must be replaced with select range_variable or for joins, an anonymous object containing all the range variables.
SELECT fields must be replaced with select new { ... } creating an anonymous object with all the desired fields or expressions.
Proper FULL OUTER JOIN must be handled with an extension method.

Invalid Identifier SQL

So i have this:
SELECT p.plantnaam,o.levcode,o.offerteprijs
FROM plant p, offerte o
JOIN (SELECT plantcode , MIN(offerteprijs) AS offprijs
FROM offerte
GROUP BY plantcode) s
ON s.plantcode = p.plantcode
AND s.offprijs = o.offerteprijs
ORDER BY p.plantnaam,l.levcode
Appearently on the 6th row, p.plantcode is suddenly magically an invalid identifier. Why is this? and why are all the others from the exact same table perfectly fine before that point?
The problem is that you are mixing JOINs. You have both implicit and explicit joins. The explicit JOIN syntax with the ON clause has a higher precedence over the implicit join with the commas. As a result the alias for the plant and the offerte tables will not be available in the ON clause. Try using the same JOIN type throughout:
SELECT p.plantnaam, o.levcode, o.offerteprijs
FROM
(
SELECT plantcode , MIN(offerteprijs) AS offprijs
FROM offerte
GROUP BY plantcode
) s
INNER JOIN plant p
ON s.plantcode = p.plantcode
INNER JOIN offerte o
ON s.offprijs = o.offerteprijs
ORDER BY p.plantnaam, l.levcode

LINQ query (or lambda expression) to return records that match a list

I have a list of strings (converted from Guid) that contains the ID's of items I want to pull from my table.
Then, in my LINQ query, I am trying to figure out how to do an in clause to pull records that are in that list.
Here is the LINQ
var RegionRequests = (from r in db.course_requests
where PendingIdList.Contains(r.request_state.ToString())
select r).ToList();
It builds, but I get a run error: "System.NotSupportedException: LINQ to Entities does not recognize the method 'System.String ToString()' method, and this method cannot be translated into a store expression".
I would prefer to compare guid to guid, but that gets me nowhere.
Can this be converted to a lambda expression? If that is best, how?
LINQ to Entites tries to convert your expression to an SQL Statement. Your server didn't know the stored procedure ToString().
Fix:
var regionRequests =
from r in db.course_requests.ToList()
where PendingIdList.Contains(r.request_state.ToString())
select r;
With db.course_requests.ToList() you force LINQ to materialize your database data (if big table, you gonna have a bad time) and the ToString() is executed in the object context.
You stated: I have a list of strings (converted from Guid) ...
Can you NOT convert them into strings and keep it as a List< System.Guid>?? Then you can do this (assuming PendingIdGuidList is List< System.Guid>:
var regionRequets = (from r in db.course_requests
join p in PendingIdGuidList on u.request_state equals p
select r).ToList();
Edited to add:
I ran a test on this using the following code:
var db = new EntityModels.MapleCreekEntities();
List<System.Guid> PendingIdGuidList =
new List<System.Guid>() {
System.Guid.Parse("77dfd79e-2d61-40b9-ac23-36eb53dc55bc"),
System.Guid.Parse("cd409b96-de92-4fd7-8870-aa42eb5b8751")
};
var regionRequets = (from r in db.Users
join p in PendingIdGuidList on r.Test equals p
select r).ToList();
Users is a table in my database. I added a column called Test as a Uniqueidentifier data type, then modified 2 records with the following Guids.
I know it's not exactly a 1:1 of what the OP is doing, but pretty close. Here is the profiled SQL statement:
SELECT
[Extent1].[ID] AS [ID],
[Extent1].[UserLogin] AS [UserLogin],
[Extent1].[Password] AS [Password],
[Extent1].[Test] AS [Test]
FROM [dbo].[Users] AS [Extent1]
INNER JOIN (SELECT
cast('77dfd79e-2d61-40b9-ac23-36eb53dc55bc' as uniqueidentifier) AS [C1]
FROM ( SELECT 1 AS X ) AS [SingleRowTable1]
UNION ALL
SELECT
cast('cd409b96-de92-4fd7-8870-aa42eb5b8751' as uniqueidentifier) AS [C1]
FROM ( SELECT 1 AS X ) AS [SingleRowTable2]) AS [UnionAll1] ON [Extent1].[Test] = [UnionAll1].[C1]

Resources