As I'm preparing a stored procedure, how can I do this in a SQL query?
This is my Linq-to-SQL code:
var passedContainers = Db.AssessmentContainers.Where(cac => cac.Assessments.All(a =>
completedContainers.FirstOrDefault(ac => ac.AssessmentId == a.AssessmentId) != null &&
completedContainers.FirstOrDefault(ac => ac.AssessmentId == a.AssessmentId).Earned));
Your question is quite a bit scarse, but with some guessing I think it could be something like that what you like to achieve:
SELECT * FROM AssessmentContainers A
INNER JOIN CompletedContainers C ON A.AssessmentId = C.AssessmentId
WHERE C.Earned = 1;
I don't have the full picture yet, but why would you like to do that with a stored procedure? Wouldn't a view be the better choice?
Related
I have this linq code that I need to translate into identical SQL so I can query the database directly... I get stuck when it gets complicated. Can anyone help?
Linq
_db.BatchPaymentSplits
.Where(bps => bps.YearSetupId == i.YearSetupId)
.Where(bps => bps.CustomerIdEntered != null)
.Where(bps => _db.BatchPayments
.Where(bp => _db.Batches.Where(b => b.BatchTypeId.Equals("T"))
.Select(b => b.BatchId)
.Contains(bp.BatchId)
)
.Select(bp => bp.BatchPaymentId).Contains(bps.BatchPaymentId)
)
SQL so far
SELECT * FROM BatchPaymentSplit
WHERE YearSetupId = 1
AND CustomerIdEntered IS NOT NULL
I can't say that I think the LINQ or the resulting SQL is the best way to express this query (should be using Join I think), but this is my literal translation:
SELECT *
FROM BatchPaymentSplits bps
WHERE bps.YearSetupId = i.YearSetupId AND
bps.CustomerIdEntered IS NOT NULL AND
EXISTS (SELECT * FROM BatchPayments bp
WHERE EXISTS (SELECT * FROM Batches b
WHERE b.BatchTypeId = 'T' AND
b.BatchId = bp.BatchId) AND
bp.BatchPaymentId = bps.BatchPaymentId)
You can translate Contains when applied to an IEnumerable/IQueryable as an EXISTS query with an = expression.
How to change the following SQL query to Linq query and how to convert results to a list of strings?
select Name
from Categories
where ID in (select CID from CategoryLink where VID = 57)
Please, provide some extra context. From the fist sight the code should be something like this:
List<string> names = db.Categories
.Where(c => db.CategoryLink.Any(cl=>cl.VID == 57 && CID == c.ID))
.ToList();
I have used too much time (days) on this and I really hope someone can help me out.
I found a good article on describing my problem in a generic way so let's stick to it.
I am trying to build this query but NHibernate fails to build the correct sql and returns a sql query exception.
Column vSagsAendring.Id is invalid in the select list because it is not contained in either an aggregate function or the GROUP BY clause. It could not execute the following query:
select
viewsagsae0_.Id as Id155_,
viewsagsae0_.SagId as SagId155_,
viewsagsae0_.JournalNr as JournalNr155_,
viewsagsae0_.LbfNr as LbfNr155_,
viewsagsae0_.OrgNr as OrgNr155_,
viewsagsae0_.OrgNavn as OrgNavn155_,
viewsagsae0_.AfdNavn as AfdNavn155_,
viewsagsae0_.SagsType as SagsType155_,
viewsagsae0_.Status as Status155_,
viewsagsae0_.SagsbehandlerInit as Sagsbeh10_155_,
viewsagsae0_.Dato as Dato155_,
viewsagsae0_.JournalAktionType as Journal12_155_,
viewsagsae0_.Beskrivelse as Beskriv13_155_,
viewsagsae0_.Ekstern as Ekstern155_
from vSagsAendring viewsagsae0_
group by viewsagsae0_.SagId
var query = from p in _session.Query<ViewSagsAendring>()
group p by p.SagId
into grp
select grp.OrderByDescending(g => g.Dato).First();
This is another version also took from the article:
var query = from p in _session.Query<ViewSagsAendring>()
group p by p.SagId
into grp
let maxDato = grp.Max(g => g.Dato)
from p in grp
where p.Dato == maxDato
select p;
It's have been a long journey, but now it's over. I hope that I can help someone else in the same situation by answering my own question.
var aendring = from sagsAendring in _session.Query<ViewSagsAendring>()
where sagsAendring.Dato ==
(
from innersagsAendring in _session.Query<ViewSagsAendring>()
where innersagsAendring.SagId == sagsAendring.SagId
select innersagsAendring.Dato
).Max()
select sagsAendring;
var result = aendring.ToList();
And because you can chain linq statements you can build a linq filter like this
if(Filters.VisInterneAendringer == false)
query = query.Where(x => x.Ekstern == true);
if (Filters.VisKunNyesteAendringer)
{
query = query.Where(sagsAendring => sagsAendring.Dato ==
(
from innerSagsAendring in Session.Query<ViewSagsAendring>() where innerSagsAendring.SagId == sagsAendring.SagId
select innerSagsAendring.Dato
).Max());
}
return query;
Your queries seem legit for LINQ in EntityFramework.
I'm not sure about hibernate, you might try to use QueryOver API instead of Query
http://nhibernate.info/blog/2009/12/17/queryover-in-nh-3-0.html
i am designing a project in asp.net mvc3.
this is my table
i want to print all information where RawMaterialID=1
please suggest me how should i write query to do this. I am using Entity Framework to access database.
You can use Lambda expression or can use sql syntax.
var results = (from x in dbContext.MaterialTable
where x.RawMaterialID == 1
select x);
Or
var results = dbContext.MaterialTable.Where(r => r.RawMaterialID == 1);
It would be something like
var results = dbContext.MyTable.Where(r => r.RawMaterialID == 1);
I've got myself in a bit of a pickle!
I've done a snazzy LINQ statement that does the job in my web app, but now I'd like to use this in a stored procedure:
var r = (from p in getautocompleteweightsproducts.tblWeights
where p.MemberId == memberid &&
p.LocationId == locationid
select p);
if (level != "0")
r = r.Where(p => p.MaterialLevel == level);
if (column == "UnitUserField1")
r = r.Where(p => p.UnitUserField1 == acitem);
if (column == "UnitUserField2")
r = r.Where(p => p.UnitUserField2 == acitem);
return r.OrderBy(p => p.LevelNo).ToList();
However, I can't for the life of me get the conditional where clause to work!!
If someone can point me in the right direction, I'd be most grateful.
Kind regards
Maybe something like this?
SELECT *
FROM dbo.weights
WHERE member_id = #memberid
AND location_id = #locationid
AND material_level = CASE WHEN #level = '0' THEN material_level
ELSE #level END
AND #acitem = CASE #column WHEN 'UnitUserField1' THEN unit_user_field_1
WHEN 'UnitUserField2' THEN unit_user_field_2
ELSE #acitem END
ORDER BY level_no
Have you tried LinqPAD, I'm pretty sure last time I played with that you could enter "LINQ to SQL" code and see the resulting SQL that produced. Failing that, place a SQL trace/profiler on your code running the LinqTOSQL and find the query being executed in the trace.
LukeH's answer will give you the correct rows, but there is something lost when you try to replace a query-generating-machine with a single query. There are parts of that query that are opaque to the optimizer.
If you need the original queries as-would-have-been-generated-by-linq, there are two options.
Generate every possible query and control which one runs by IF ELSE.
Use Dynamic sql to construct each query (although this trades away many of the benefits of using a stored procedure).
If you do decide to use dynamic sql, you should be aware of the curse and blessings of it.