MSSQL Query Not Returning Null Columns/Results - c#

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

Related

How do I do a right join and return only null values in EntityFramework?

I have two tables, NAttrValues and NAttrTitles. The NAttrTitles have an ID, which is referenced in the NAttrValues table by the column 'TitleID'. I'm trying to return the elements in NAttrTitles that do not have any associated NAttrValues, using LINQ in EntityFramework.
This SQL query returns exactly what I want
SELECT * FROM NAttrValues nav RIGHT JOIN NAttrTitles nat ON nav.TitleID = nat.ID WHERE nav.TitleID IS NULL
How do I write this in EntityFramework? I've tried various different uses of .DefaultIfEmpty() but they all end up returning either the wrong thing, or nothing at all.
Right Outer Join is the same as Left Outer Join with left and right sides swapped. So the LINQ To Entities equivalent of your SQL query is:
var query =
from nat in db.NAttrTitles
join nav in db.NAttrValues on nat.ID equals nav.TitleID into nat_nav
from nav in nat_nav.DefaultIfEmpty()
where nav == null
select nat;

linq query displaying result twice

pd is my page ;
ProductDetail pd = new ProductDetail();
fetching data and strong it in data
var data =
from product in db.Products
from orders in db.Orders
from od in db.OrderDetails
from dpt in db.Dpts
where orders.CId.Equals(
(from name in db.Companies
where name.Cname.Equals(selectedcomp)
select name.CId).FirstOrDefault())
&& od.OrdId.Equals(orders.OrdId)
&& product.PId.Equals(od.PId)
select new
{
orders.Billno ,
orders.Date,
orders.pharm ,
product.Pname,
product.Purchasedate,
product.Purchaserate,
product.Salesrate,
product.Supplier,
od.Quantity,
od.Amount
};
it displays the value of data twice in listbox.
pd.ProductDescription.ItemsSource =
(from dat in data
select dat).ToList();
I think your problem is the cross join to the Dpts table. You don't use the results from that table in the where or select, so I don't think you need it. Try removing from dpt in db.Dpts and see if that fixes your problem. My guess is that you are getting n duplicates where n is the total number of rows in db.Dpts.
#juharr is right. You don't use db.Dbts in where clause, so you cross join duplicates results. Probably in db.Dbts table you have 2 records.
I think that you should work on your query.
Few tips:
We don't use cross joins, rather we use join statement
You should get CId before executing your main query
Probably You don't have foreign keys in your database, you should consider that
When getting duplicate items from a query in LINQ or SQL, first check for bad data, then investigate it as a bad join. Your best bet is to strip it down to one table, then add the joins in one-by-one until you get your duplication. Then make that join specific enough that it stops duplicating.

Efficient way to count related entities of a many to many relation in EF

I would like to know how to efficiently count (SQL server side) the amount of distinct count of results for a specific range of a related entity that has a many to many relationship.
This is the current situation in entity Framework:
Table1 1<------->∞ Table2
Table2 ∞<------->∞ Table4
Table 2 and Table 4 have a many to many relationship and are linked with Table3 in SQL.
What I want is the distinct count of table4 results related to a specific range of Table1.
In LinQ to SQL the query is this:
(from dc in Table1
join vc in Table2 on dc.Table1Id equals vc.Table2Id
join vcac in Table3 on vc.Table2Id equals vcac.Table3Id
join ac in Table4 on vcac.Table3Id equals ac.Table4Id
where dc.Table1Id > 200000
group ac by ac.Table4Id into nieuw
select new { acid= nieuw.Key}).Count()
This lets SQL server return the count directly.
Because the extra table for the many to many relation ( Table3) is gone, I have had problems converting this query to L2E in query syntax. ( since I cannot join table 4 with table 2 with an inner join).
I have this in chained syntax, however, is this efficient ( does this fetch the whole list, or does it let SQLserver do the count, as I'm not sure this is an efficient way to select, Table 2 contains about 30.000 entries, I don't want it to fetch this result just to count it):
context.Table4.Where(a => a.Table2.Any(v => v.Table1Id > 200000)).Select(a => aTable4Id).Distinct().Count();
How would I go converting the Linq2SQL query into L2E in the query syntax ? Or is the chained syntax fine in this situation ?
The .Select() method uses deferred execution, meaning it won't actually run the query until you need the results. At that point in the chain it still exists only as a query definition. Then you modify with .Distinct() before getting .Count() - which does query the database using a SQL GROUP BY statement. So you should be good.

Joining PIVOT table with data from two other tables with ACCESS

I'm having trouble with joining a pivot table with data from two other tables. The pivot table works fine but when I join it it says 'Syntax error in FROM clause'
SELECT r.resourceName AS 'Employee Name',
p.projectNumber AS 'Project Number',
p.projectSystem AS 'Project System',
p.projectManager AS 'Project Manager',
a.projectName AS 'Project Name'
FROM Projects p
LEFT JOIN
(TRANSFORM SUM(a.AllocationValue)
SELECT r.ResourceName, a.ProjectName
FROM Resources r
GROUP BY a.ResourceName, a.ProjectName
PIVOT a.AllocationMonth IN ('June, 2014', 'July, 2014', 'August, 2014') q
ON p.resourceName = q.resourceName
WHERE p.projectName = a.projectName
ORDER BY r.resourceName, a.projectName
Any help would be appreciated, thanks!
I don't think you can have a combination of implicit and explicit joins, and you are also aliasing both the table Projects as p, and the subquery as p.
Instead of FROM Projects p, Resources r, which is an implicit join, you should make that an explicit join FROM Projects p JOIN Resources r ON p.whatever = r.whatever, and then change the alias of your subquery so it isn't also named p.
You also have Resources aliased as r in both the outer query and the subquery, and that's a conflict.
Those are the issues I see right off the bat.
It appears that you are joining an aliased subquery "p" to another aliased as "q". Therefore, your join "ON p.resourceName = r.resourceName" should be "ON p.resourceName = q.resourceName".
Both the WHERE and ORDER BY also appear incorrect.
Have you tried constructing individual queries in the query editor, saving them, then constructing the final query? Examining the resultant sql (query > sql view) should help you.

How to use JOIN on database.

(SQLite and C#)
I have this little problem. See those 2 tables. 1. is parent, 2. is child
I should get "broj_goluba" from parent table to match "par_m" and "par_z" in child table and later just display it in datagridview.
Foregin keys should help to get things done fast, but here when I write code I have much more lines of code opposed to not using foreign keys.
Could someone please help me and write down how my code (EDIT: SQL query) should look like when using foreign keys.
What I understand you need is that, but it doesn't have to do anything with speed. Maybe you mean INDEX and not FOREIGN KEY.
SELECT BROJ_GOLUBA
FROM TABLE1
INNER JOIN TABLE2 ON (TABLE1.ID = TABLE2.PAR_M OR TABLE1.ID = TABLE2.PAR_J)
Or maybe you need BOTH values to be equal:
SELECT BROJ_GOLUBA
FROM TABLE1
INNER JOIN TABLE2 ON (TABLE1.ID = TABLE2.PAR_M AND TABLE1.ID = TABLE2.PAR_J)
Foreign keys don't exist to "help to get things done fast". They exist to enforce data integrity. Frankly, I don't see how the number of lines of T-SQL code you write is dependent on whether or not foreign keys exist.
The following query stub should help get you started on your query:
Select Table1.broj_goluba, Table2.par_z ...
From Table1
Inner Join Table2 on Table1.ID = Table2.par_m

Categories