Linq to SQL Case WHEN in VB.NET? - sql

How do I do a Case WHEN in Linq to SQL (vb.net please).
In SQL it would be like this:
SELECT
CASE
WHEN condition THEN trueresult
[...n]
[ELSE elseresult]
END
How would I do this in Linq to SQL?

var data = from d in db.tb select new {
CaseResult = If (d.Col1 = “Case1”, "Case 1 Rised", If (d.Col1 = “Case2”, "Case 2 Rised", "Unknown Case"))
};

Check This Out
var data = from d in db.tb select new {
CaseResult = (
d.Col1 == “Case1” ? "Case 1 Rised" :
d.Col1 == “Case2” ? "Case 2 Rised" :
"Unknown Case")
};
Please Note that [ ? Symbol = then] , [ : Symbol = Or].

I haven't tried this but you may be able to do something like:
Dim query = From tbl In db.Table _
Select result =_
If(tbl.Col1 < tbl.Col2,"Less than",_
If(tbl.Col1 = tbl.Col2,"Equal to","Greater than"))
You would just need to keep nesting the If functions to handle all of your cases.
You can find more examples of various queries at http://msdn.microsoft.com/en-us/library/bb386913.aspx

Related

Raw Expression in Laravel?

My sql code is :
Select * from table where cond(condition)1 and con2 ...... and(conX or conY).
How can i write it with raw expression. I don't know the keywork to solve this.
Update: My code is :
//$builder->to sql = Select * from table where cond(condition)1 and con2 ...... ;
if(something != true) $builder->whereRaw(conX);
else $builder->whereRaw((conX or ConY));
//$builder->to sql = Select * from table where cond(condition)1 and con2 ...... and (conX or conY);
OK, it work, but i need to write conX 2 times, though it too long. So now i want to contract it.
//$builder->to sql = Select * from table where cond(condition)1 and con2 ...... and conX;
if(something = true) $builder->raw or do something; (#)
//$builder->to sql = Select * from table where cond(condition)1 and con2 ...... and (conX or conY);
The question is that: What i should do in the (#) line to make the result as i expected
Try:
if (something == true) {
$result = DB::table('table')
->selectRaw('*')
->where(condition1)
->where(condition2)
->get();
}
Or:
if (something == true) {
$result = DB::table('table')
->select(DB::raw(YOUR SQL STATEMENT))
->get();
}
Further read:
https://laravel.com/docs/5.5/queries

Need help in converting SQL query to LINQ

I am new to the world of LINQ and hence I am stuck at converting one sql query to LINQ.
My SQL query is:
select COUNT(DISTINCT PAYER) as count,
PPD_COL FROM BL_REV
where BL_NO_UID = 1084
GROUP BY PPD_COL
The desired output is:
Count PPD_COL
12 P
20 C
I have written something like below in LINQ:
var PayerCount = from a in LstBlRev where a.DelFlg == "N"
group a by new { a.PpdCol} into grouping
select new
{
Count = grouping.First().PayerCustCode.Distinct().Count(),
PPdCol = (grouping.Key.PpdCol == "P") ? "Prepaid" : "Collect"
};
But it is not giving me the desired output. The count is returned same for PPD_COL value P & C. What am I missing here?
Change the groupby as following. in the group group only the property you need and then in thr by no need to create an anonymous object - just the one property you are grouping by.
var PayerCount = from a in LstBlRev
where a.DelFlg == "N"
group a.PayerCustCode by a.PpdCol into grouping
select new
{
Count = grouping.Distinct().Count(),
PPdCol = grouping.Key == "P" ? "Prepaid" : "Collect"
};

Dynamic where in a Sql Select Query

i would like to create a sql query like these :
Select* from Table where
(if picod=1)
{
dvdt= "xxxx"
}
(if picod=2)
{
cddt= "xxxx"
}
(if picod=3)
{
bldt= "xxxx"
}
(if picod=3)
{
fadt= "xxxx"
}
I don't know how doing this in SQL .
Anyone could help me please ?
Thanks a lot :)
Select* from Table
where (picod=1 and dvdt= 'xxxx') or (picod=2 and cddt= 'xxxx') or ....... (XXXX) or....
Just use OR
SELECT *
FROM Table
WHERE (Picod = 1 AND dvdt = 'xxxx')
OR (Picod = 2 AND cddt = 'xxxx')
OR (Picod = 3 AND bldt = 'xxxx')
OR (Picod = 3 AND fadt = 'xxxx');
SELECT *
FROM Table
WHERE 'xxxx' = case Picod
when 1 then dvdt
when 2 then cddt
when 3 then bldt
when 4 then fadt
end

Optimize Linq to SQL query, Group By multiple fields

My LINQ query contains the following Group By statement:
Group p By Key = New With { _
.Latitude = p.Address.GeoLocations.FirstOrDefault(Function(g) New String() {"ADDRESS", "POINT"}.Contains(g.Granularity)).Latitude, _
.Longitude = p.Address.GeoLocations.FirstOrDefault(Function(g) New String() {"ADDRESS", "POINT"}.Contains(g.Granularity)).Longitude}
The query works, but here is the SQL that the clause above produces
SELECT [t6].[Latitude]
FROM (
SELECT TOP (1) [t5].[Latitude]
FROM [dbo].[GeoLocations] AS [t5]
WHERE ([t5].[Granularity] IN (#p0, #p1)) AND ([t5].[AddressId] = [t2].[Addr_AddressId])
) AS [t6]
) AS [value], (
SELECT [t8].[Longitude]
FROM (
SELECT TOP (1) [t7].[Longitude]
FROM [dbo].[GeoLocations] AS [t7]
WHERE ([t7].[Granularity] IN (#p2, #p3)) AND ([t7].[AddressId] = [t2].[Addr_AddressId])
) AS [t8]
) AS [value2]
I am not a SQL expert, but it looks to me that this is rather suboptimal translation. This should really be one query that selects Latitide and Longitude from the first record. Perhaps SQL Server Optimizer will take care of this. But is there a way to nudge Linq to generate a leaner SQL statement to begin with?
I tried the following, too..
Group p By Key = p.Address.GeoLocations.Where(Function(g) New String() {"ADDRESS", "POINT"}.Contains(g.Granularity)). _
Select(Function(g) New With {.Latitude = g.Latitude, .Longitude = g.Longitude}).FirstOrDefault
but this produced an error: "A group by expression can only contain non-constant scalars that are comparable by the server."
Sorry to reply in c#...
Here's what you have, translated to c#:
List<string> params = new List<string>()
{ "Address", "Point" };
from p in people
group p by new {
Latitude = p.Address.GeoLocations
.FirstOrDefault(g => params.Contains(g.Granularity)).Latitude,
Longitude = p.Address.GeoLocations
.FirstOrDefault(g => params.Contains(g.Granularity)).Longitude
};
Here's a rewrite, using the let keyword.
from p in people
let loc = p.Address.GeoLocations
.FirstOrDefault(g => params.Contains(g.Granularity))
group p by new
{
Latitude = loc.Latitude,
Longitude = loc.Longitude
};

Sql Query to Linq

How would I convert this query from SQL to Linq:
SELECT status As 'Status',
count(status) As 'Count'
FROM tbl_repair_order
WHERE contract = 'con' and
(status = 'Parts Arr' or
status = 'NA' or
status = 'New Call' or
status = 'Parts Ord' or
status = 'Parts Req' or
status = 'F Work')
GROUP BY status
Update
Thanks Guys, this is the code I used. Tested and returns the same as above:
List<string> statuses = new List<string> { "Parts Arr", "NA", "New Call", "Parts Ord", "Parts Req", "F Work"};
var result = (from x in db.tbl_repair_orders
where x.CONTRACT == strContract
&& statuses.Contains(x.STATUS)
group x.STATUS by x.STATUS into grouping
select new { Status = grouping.Key, Count = grouping.Count() });
return result;
string[] statuses = new string[] { "Parts Arr", "NA", "New Call", "Parts Ord", "Parts Req", "F Work" };
var x = (from ro in db.tbl_repair_order
where ro.contract == "con"
&& statuses.Contains(ro.status)
group 0 by ro.status into grouping
select new { Status = grouping.Key, Count = grouping.Count() });
I don't know if the syntax is correct (especially the last two lines) but it should be pretty close.
I added the 0 between group and by based on Eamon Nerbonne's correction in the comments. Also, thanks to Ryan Versaw for the link explaining List and arrays for generating IN clauses.
Assuming you wire up your table's appropriately, something like
var statusCounts =
from row in youDbNameHere.tbl_repair_order
where row.contract == "con"
&& (row.status == "Parts Arr"
|| row.status == "NA"
|| row.status == "New Call"
|| row.status == "Parts Ord"
|| row.status == "Parts Req"
|| row.status == "F Work")
group 0 by row.status into g
select new { Status = g.Key, StatusCount = g.Count() };
...and I see Andy beat me to it ;-)
Notes:
You need to include an expression between "group" and "by", this expression is will be evaluated to form the set of values accessible under the group's key (in your case it's irrelevant, so a zero is fine).
If you wish to use Linq-to-Sql or Linq-to-Entities (or some other IQueryable implementation), be aware that your code will not execute directly in C#, but rather be translated (as it should be) into sql -- so avoid using .NET specific calls that cannot be translated, as these will generally cause a run-time exception or (rarely) cause the resulting query to be partially evaluated client-side (at a potentially hefty performance cost).
As far a s converting SQL statements to equivalent Linq to SQL statements you should check out the Linqer tool which does just that. I don't think this app is good to use for re-writting your whole application but it can be a very useful tool for learning Linq to SQL in general.