Derived tables in Linq to SQL - sql

I would like to implement this in Linq to SQL:
select * from (
select * from Orders) as A
Obviously this is a pointless example, but I just can't figure out how to do it!

Try something like this:
var subquery = from row in Orders select row;
var query = from row in subquery select row;

using (var dc = new NorthwindDataContext())
{
var A = from ordOuter in
from ordInner in dc.Orders
select ordInner
select ordOuter;
}

Related

SQL Server Procedure Parameter List [duplicate]

Say I have the a table with 3 columns : Id, Category, Name.
I would like to query the table that way :
Get me the rows for which
{ Category = "Cat1" AND Name = "ABC" } OR { Category = "Cat2" AND Name = "ABC" } OR { Category = "Cat2" AND Name = "DEF" }
How? Without having to resort to a huge list of WHERE OR
I was thinking of using IN...but is it possible to use that in conjunction with 2 columns?
Thanks!
You can create a temp table
create table #temp (Category varchar(50), Name varchar(50))
insert into #temp values ('Cat1', 'abc'), ('Cat2', 'cde'), ('Cat3', 'eee')
And then join your main table
select * from table1
inner join #temp
on table1.Category = #temp.Category and table1.Name = #temp.Name
If you want to use that approach from the code, you can do that using table parameters.
Define a table type:
CREATE TYPE dbo.ParamTable AS TABLE
( Category varchar(50), Name varchar(50) )
and a stored proc that will read the data:
create procedure GetData(#param dbo.ParamTable READONLY)
AS
select * from table1
inner join #param p
on table1.Category = p.Category and table1.Name = p.Name
Then you can use those from the C# code, for example:
using (var conn = new SqlConnection("Data Source=localhost;Initial Catalog=Test2;Integrated Security=True"))
{
conn.Open();
DataTable param = new DataTable();
param.Columns.Add(new DataColumn("Category", Type.GetType("System.String")));
param.Columns.Add(new DataColumn("Name", Type.GetType("System.String")));
param.Rows.Add(new object[] { "Cat1", "abc" });
using (var command = conn.CreateCommand())
{
command.CommandText = "GetData";
command.CommandType = CommandType.StoredProcedure;
command.Parameters.AddWithValue("#param", param);
using (var reader = command.ExecuteReader())
{
// reading here
}
}
}
#Szymon's answer is the best, but if you absolutely need to do it in one query you can come up with a scheme to concatenate the two columns into one string and join candidate values using the same method. Then you can use IN instead of a bunch of ANDs and ORs.
SELECT *
FROM table
WHERE Category + ':' + Name IN ('Cat1:abc', 'Cat2:cde', 'Cat3:eee')
This has the distinct disadvantage of never being able to take advantage of indexes. But it's good for a quick and dirty solution.
With Sql2008 there is an interesting new clause VALUES in FROM:
select *
from mytable
inner join ( select * from (values('cat1', 'abc'),
'cat2', 'def') as T(cat,name) ) C
on mytable.category = c.cat and mytable.name = c.name
Create temporary table to store the key value pairs. Then query from your main table joinned with temporary table. Not as simple as adding IN(...), but this is the only way I can think and i believe IN(...) is not capable

How to query the database with a list of key-value pairs

Say I have the a table with 3 columns : Id, Category, Name.
I would like to query the table that way :
Get me the rows for which
{ Category = "Cat1" AND Name = "ABC" } OR { Category = "Cat2" AND Name = "ABC" } OR { Category = "Cat2" AND Name = "DEF" }
How? Without having to resort to a huge list of WHERE OR
I was thinking of using IN...but is it possible to use that in conjunction with 2 columns?
Thanks!
You can create a temp table
create table #temp (Category varchar(50), Name varchar(50))
insert into #temp values ('Cat1', 'abc'), ('Cat2', 'cde'), ('Cat3', 'eee')
And then join your main table
select * from table1
inner join #temp
on table1.Category = #temp.Category and table1.Name = #temp.Name
If you want to use that approach from the code, you can do that using table parameters.
Define a table type:
CREATE TYPE dbo.ParamTable AS TABLE
( Category varchar(50), Name varchar(50) )
and a stored proc that will read the data:
create procedure GetData(#param dbo.ParamTable READONLY)
AS
select * from table1
inner join #param p
on table1.Category = p.Category and table1.Name = p.Name
Then you can use those from the C# code, for example:
using (var conn = new SqlConnection("Data Source=localhost;Initial Catalog=Test2;Integrated Security=True"))
{
conn.Open();
DataTable param = new DataTable();
param.Columns.Add(new DataColumn("Category", Type.GetType("System.String")));
param.Columns.Add(new DataColumn("Name", Type.GetType("System.String")));
param.Rows.Add(new object[] { "Cat1", "abc" });
using (var command = conn.CreateCommand())
{
command.CommandText = "GetData";
command.CommandType = CommandType.StoredProcedure;
command.Parameters.AddWithValue("#param", param);
using (var reader = command.ExecuteReader())
{
// reading here
}
}
}
#Szymon's answer is the best, but if you absolutely need to do it in one query you can come up with a scheme to concatenate the two columns into one string and join candidate values using the same method. Then you can use IN instead of a bunch of ANDs and ORs.
SELECT *
FROM table
WHERE Category + ':' + Name IN ('Cat1:abc', 'Cat2:cde', 'Cat3:eee')
This has the distinct disadvantage of never being able to take advantage of indexes. But it's good for a quick and dirty solution.
With Sql2008 there is an interesting new clause VALUES in FROM:
select *
from mytable
inner join ( select * from (values('cat1', 'abc'),
'cat2', 'def') as T(cat,name) ) C
on mytable.category = c.cat and mytable.name = c.name
Create temporary table to store the key value pairs. Then query from your main table joinned with temporary table. Not as simple as adding IN(...), but this is the only way I can think and i believe IN(...) is not capable

Linq Left Join returns repeated same rows for all set

my linq returns all repeated same rows for all set
run SQL in DB :
select top 20 * from t1
left join t2
on t1.sid= t2.sid
and t1.pid=t2.pid
where(t2.sid is null and t1.pid='r')
i can get 20 different rows of result.
then i write Linq:
Entities dbconn = new Entities();
List<t1> myResult = (
from t1Data in dbconn.t1
join t2Data in dbconn.t2
on new { sid = (int)t1.sid, pid= t1.pid}
equals new { sid= (int)t2.sid, pid= t2.pid}
into joinSet
from joinUnit in joinSet.DefaultIfEmpty()
where (joinUnit == null) && (t1.pid== "r")
select t1Data
).Take(20).ToList();
all rows of result are the some row.
select t1Data is wrong as t1Data is from the original dataset.
Instead, select the joined result: select joinSet.

The Translation of an SQL query to LinQ

Due to wierd request from a Customer, I have managed to figure out how to implement it
using SQL query, but I couldn't translate it into LinQ.
SELECT (SELECT count(*) FROM table1 where attribute1 like 'value1'),
(SELECT count(*) FROM table2 where attribute2 like 'value2')
What the translation of the query to LinQ?
You could just supply a predicate to the Count() function
var result = new {
Count1 = table1.Count(r => r.attribute1.Contains("value1")),
Count2 = table2.Count(r => r.attribute2.Contains("value2"))
};
var count1 = (from i in table1 where SqlMethods.Like(i.attribute1, "value1") select i).Count();
var count2 = (from i in table2 where SqlMethods.Like(i.attribute2, "value2") select i).Count();

php sql merge 2 queries

I have 2 queries one straight after the other:
$sql_result8 = mysql_query("SELECT * FROM properties WHERE c4='$id'", $db); $charges = mysql_num_rows($sql_result8);
$sql_result8 = mysql_query("SELECT * FROM vehicles WHERE c4='$id'", $db); $charges = $charges + mysql_num_rows($sql_result8);
What kind of query would I need to merge these? Some kind of JOIN? UNION?
SELECT * FROM properties p, vehicles v WHERE p.c4 = v.c4 AND p.c4 = '$id'
Try this
SELECT * FROM properties JOIN vehicles USING (c4) WHERE c4='$id'
If you want to just find out the number or rows returned from both queries and not show the actual columns, you can use this:
$sql_result8 = mysql_query(
"SELECT
( SELECT COUNT(*) FROM properties WHERE c4='$id' )
+ ( SELECT COUNT(*) FROM vehicles WHERE c4='$id' )
", $db );