Using C# and ASP.NET, I need my gridview to draw columns from multiple tables. How do I do this? I currently have
`SelectCommand="SELECT [SubId], [CustName], [CustCity] FROM [Customer]">
</asp:SqlDataSource>`
as my select statement, but I need to select from two more tables. What is the syntax?
apologies for being unclear before.
Your SelectCommand should be the same statement that you would execute if you were running the query on the database directly. So, in your case, you would want something like:
SELECT [SubId], [CustName], [BroName], [Entity]
FROM [Customer]
JOIN [Broker] ON <join condition>
JOIN [Submission] ON <join condition>
If you don't need to update the SqlDataSource, you can simply put JOINS into your query.
For example:-
Select CustFld1, CustFld2, OrdFld1, OrdFld2 from Cust inner join Ord on CustPKeyFld=OrdCustFKeyField
If you do need to update the SqlDataSource, you need to use sub-queries to return the data that would otherwise be returned in the join
For example:-
Select CustFld1, CustFld2, (Select OrdFld1 from Ord where OrdCustFkeyFld=CustPKeyFld) as OrdFld1, (Select OrdFld2 from Ord where OrdCustFKeyFld=CustPKeyFld) as OrdFld2 from Cust
Related
I'm kind of new to SQL queries so this is probably something easily fixed, but I can't seem to find any answers.
I've got a bunch of related tables. E.g.
SPClients contains iClientID and sName, SPDocTypes contains iDocTypeID and sName, SPCreditor contains iCreditorID and sName
and then
SPDocIndex contains iIndexID, and then foreign keys to iClientID, iDocTypeID and iCreditorID listed above.
If I do a simple SELECT * FROM SPDocIndex I get all results, with just the IDs being displayed, which isn't much use when bound to a datagrid. So I use an inner join so the actual names appear rather than just their IDs, like so:
SELECT * FROM SPDocIndex
INNER JOIN SPClients ON SPDocIndex.iClientID=SPClients.iClientID
INNER JOIN SPDocType ON SPDocIndex.iDocTypeID=SPDocType.iDocTypeID
INNER JOIN SPCreditor ON SPDocIndex.iCreditorID=SPCreditor.iCreditorID
And the query "works" but it only returns rows that have data in all three columns. If the iCreditorID column of SPDocIndex is null, then that row is NOT returned...but I would like all rows to be returned irrespective of whether the columns are null or not.
Benny - some of the others responded in the comments, that you'll need to adjust your join to a left join instead of an inner join; indeed, that is the case here. Please check out this link for a quick tutorial on the differences between SQL joins.
https://www.w3schools.com/sql/sql_join.asp
Inner Join will always return the return the matching records within two table. In order to get the all the records from first table and matching record of second table you must use left join as shown below. Please try below and let me know if you have any further issues.
SELECT * FROM SPDocIndex
LEFT JOIN SPClients ON SPDocIndex.iClientID=SPClients.iClientID
LEFT JOIN SPDocType ON SPDocIndex.iDocTypeID=SPDocType.iDocTypeID
LEFT JOIN SPCreditor ON SPDocIndex.iCreditorID=SPCreditor.iCreditorID
I have a database with multiple tables and some stored procedures that query if to get specific data from various tables in order to display desired information.
Find one example of a stored procedure bellow:
SELECT DISTINCT
ROW_NUMBER() OVER (ORDER BY dbo.[table1].ReportedDate DESC) AS rowNumber,
dbo.[table1].[id],
dbo.[table1].caseReference,
dbo.[table2].organisationName AS customerName,
dbo.[table3].assetRegistration,
dbo.[table4].surname
FROM dbo.[table1] WITH (NOLOCK)
LEFT JOIN dbo.[table2] with (NOLOCK)
ON dbo.[table2].JobId = dbo.[table1].[id]
LEFT JOIN dbo.[table3] WITH (NOLOCK)
ON dbo.[table3].id = dbo.[table2].[JobServiceId]
LEFT JOIN dbo.[table4] WITH (NOLOCK)
ON dbo.[table4].[jobID] = dbo.[table1].[id]
WHERE (table1.caseReference LIKE #caseReference+'%')
I want to move from using such stored procedures to a more code based approach using entity framework. How can I recreate a query like the one above using Linq query over the dbContext classes mapped to the database?
I am mostly having problems in figuring out how to choose the data I want to be returned from each table and how to put it all together.
you can do it easly Linq query or lambda expressions over the dbContext classes mapped to the database.
check this it would be help you
Entity Framework Join 3 Tables
How to join multiple tables?
T-SQL Query
Select * from dbo.User_Users
Where UserID IN (Select UserID from Course_Enrollments)
LINQ to Entities alternative of Above Query
var innerquery = from en in Course_Enrollments
select en.UserID;
var query = from u in User_Users
where innerquery.Contains(u.UserID)
select u;
There are alot of complex subqueries on stackoverflow, i just want to see a simple example of how a simple subquery is done via linq.This is how i done it, however its not good because it sends 2 queries to the database.
Simple answer is use the "let" keyword and generate a sub-query that supports your conditional set for the main entity.
var usersEnrolledInCourses = from u in User_Users
let ces = from ce in Course_Enrollments
select ce.UserID
where ces.Contains(u.UserID)
select u;
This will create an exists block in TSQL similar to
SELECT [Extent1].*
FROM dbo.User_Users AS Extent1
WHERE EXISTS (SELECT 1 AS [C1]
FROM dbo.Course_Enrollements AS Extent2
WHERE (Extent2.UserID = Extent1.UserId))
It's close to what you've asked for and will generally create the same query plan on SQL Server.
Hope this helps!
from u in User_Users
where u.Course_Enrollments.Any()
select u
if you have the foreign keys set up. If not you can do this
from u in User_Users
join cu in Course_Enrollments on u.UserId equals cu.UserId
select u
You also should wrap any of these with .Distinct() call
I created an Entity Framework model that contains two tables from the Northwind database to test some of its functionality: Products and CAtegories.
It automatically created an association between Category and Product which is 0..1 to *.
I wrote this simple query:
var beverages = from p in db.Products.Include("Category")
where p.Category.CategoryName == "Beverages"
select p;
var beverageList = beverages.ToList();
I ran SQL Profiler and ran the code so i could see the SQL that it generates and this is what it generated:
SELECT
[Extent1].[ProductID] AS [ProductID],
[Extent1].[ProductName] AS [ProductName],
[Extent1].[SupplierID] AS [SupplierID],
[Extent1].[QuantityPerUnit] AS [QuantityPerUnit],
[Extent1].[UnitPrice] AS [UnitPrice],
[Extent1].[UnitsInStock] AS [UnitsInStock],
[Extent1].[UnitsOnOrder] AS [UnitsOnOrder],
[Extent1].[ReorderLevel] AS [ReorderLevel],
[Extent1].[Discontinued] AS [Discontinued],
[Extent3].[CategoryID] AS [CategoryID],
[Extent3].[CategoryName] AS [CategoryName],
[Extent3].[Description] AS [Description],
[Extent3].[Picture] AS [Picture]
FROM [dbo].[Products] AS [Extent1]
INNER JOIN [dbo].[Categories] AS [Extent2]
ON [Extent1].[CategoryID] = [Extent2].CategoryID]
LEFT OUTER JOIN [dbo].[Categories] AS [Extent3]
ON [Extent1].[CategoryID] = [Extent3].[CategoryID]
WHERE N'Beverages' = [Extent2].[CategoryName]
I am curious why the query inner joins to Categories and then left joins to it. The select statement is using the fields from the left joined table. Can someone help me understand the reason for this? If I remove the left join and change the select list to pull from Extent2 I get the same results for this query. In what situation would this not be true?
[Extent3] is a realization of Include(Category) and Include should not impact on result of selection from "main" table Product, so LEFT JOIN (all records from Product and some records from the right table Category).
[Extent2] is really to filter all records by related table Category with name "Beverages", so in this case it is the strong restriction (INNER JOIN)
Why two? :) Because of parsing expression-by-expression and auto generation for every statement (Include, Where)
You'll notice that the query is pulling all columns in the SELECT list from the copy of the Categories table aliased Extent3, but it's checking the CategoryName against the copy aliased Extent2.
In other words, in this scenario EF's query generation is not realizing that you're Include()ing and restricting the query via the same table, so it's blindly using two copies.
Unfortunately, beyond explaining what's going on, my experience with EF is not advanced enough to suggest a solution...
djacobson and igor explain pretty well why this happens. The way I personally use the Entity Framework, I avoid using Include altogether. Depending on what you're planning to do with the data, you could do something like this:
var beverages = from p in db.Products
select new {p, p.Category} into pc
where pc.Category.CategoryName == "Beverages"
select pc;
return beverages.ToList().Select(pc => pc.p);
... which, at least in EF 4.0, will produce just a single inner join. Entity Framework is smart enough to make it so that the product's Category property is populated with the category that came back from the database with it.
Of course, it's very likely that SQL Server optimizes things away so this won't actually gain you anything.
(Not directly an answer to your question if the queries are the same, but the comment field is too restricting for this)
If you leave out the .Include(), doesn't it load it anyway (because of the where)? Generally it makes more sense to me to use projections instead of Include():
var beverages = from p in db.Products.Include("Category")
where p.Category.CategoryName == "Beverages"
select new { Product = p, Category = p.Category };
var beverageList = beverages.ToList();
I have an application in which I am using a stored procedure and LINQ.
My procedure looks like this:
myProc
select col1, Col2, Col3 from Tab1 inner join Tab2 on col1=ColA join tab3 on Col1=ColD
Select cola, Colb, Colc from Taba inner join Tabb on cola=ColX join tabc on Cola=ColY
Select colP, ColQ, ColR from TabP inner join TabQ on colP=ColW join tabR on ColP=ColZ
I am executing this stored procedure in LINQ.
When I execute it I am getting the results in IMultipleResults.
Below is my code in LINQ:
[Function(Name = "dbo.MyProc")]
[ResultType(typeof(TabA))]
[ResultType(typeof(TabB))] .....
public IMultipleResults GetMultipleResults([Parameter(DbType = "VarChar(50)")] string i_Cola)
{
IExecuteResult result = this.ExecuteMethodCall(this, ((MethodInfo)(MethodInfo.GetCurrentMethod())), i_Cola);
return (IMultipleResults)result.ReturnValue;
}
When I execute it as follows:
MyContext mCtx = new MyContext()
var allResult = mCtx.GetMultipleResults(txtName.Text.Trim());
IEnumerable<Taba> TabaRes = allResult.GetResult<Taba>();
IEnumerable<TabB> TabbRes = allResult.GetResult<Tabb>();
I am getting the column values of tables but I want the Inner Joined columns also.
I've referred to many blogs and forums, such as...
Ben Hall's Blog
Guy Burstein's Blog
Microsoft's Blog
... to try to find a solution to my problem, but couldn't find any.
well better to use views in respect to SP(If u are not able to write a linq to sql query),if u are using Linq to Sql its worthLess to use Sp becoze it decrease the performance.and one more thing if u are using Linq to sql there is no Need to use any type of join if ur data base is completely normalized.
If still ur prob is not solved just show me the table structure and what the out u need i will write a query for u...
I am not sure I understand your need, but can you change the proc to return * or all the columns in all the tables you need?
If the stored procedure isn't returning the data required then the only option for LINQ would be for it to go query the database again itself.
This would mostly negate the point of having a stored procedure and be slower than just adding the required parameters to your stored procedure.
Maybe this would be a stupid question, but in your store procedure:
select col1, Col2, Col3 from Tab1
inner join Tab2 on col1=ColA join
tab3 on Col1=ColD
col1,col2,col3 are all from tab1, but you never did a select from the other tables that you are trying to do inner join. Did you tried
select col1,col2,col3,colA,colB...
-or-
select * from...