Getting Value From Another Table with a Foreign Key - c#

I've built a report with the report wizard in C#, and I can see my report in ReportViewer. My problem is that I have 2 tables that are related. The value of a column in the first table is a foreign key on the other table. All I see in that column is just the foreign key. I'd like to see the corresponding value from the other table.
How can I see value of the column from the second table?

You should just join on the foreign key columns:
SELECT
a.*,b.YourNeededColumnHere
FROM TableA a
INNER JOIN TableB b ON a.columnX=b.columnX
However, if you are having problems doing this in reporting services, just create a view:
CREATE VIEW CombinedAB
AS
SELECT
a.*,b.YourNeededColumnHere
FROM TableA a
INNER JOIN TableB b ON a.columnX=b.columnX
GO
you should now be able to run your report off the CombinedAB view as:
SELECT
*
FROM CombinedAB
WHERE ...your conditions here...

sounds like you probably need a drill down report
Create Basic Drilldown Report

Regarding the control that renders the result... Does it have its columns bound manually / is it set to auto-bind?

Change your query to one that involves the fields from the appropriate tables.
SELECT t1.*, t2.value
FROM table1 t1
JOIN table2 t2 ON t1.t2id = t2.id
But if you can't, because the data sources are separate, then you'll be wanting another option.
Assuming you have two datasets, from separate data sources.
Put a table in your report to show information from DataSet1 (or whatever it's called). Then put a rectangle in place of one of your textboxes, and then put a table in there, which you attach to DataSet2. Then put a filter on this table, so that it only shows records from DataSet2 which correspond to the appropriate value in DataSet1.
Or, wait for SQL Server 2008 R2 (currently in CTP), which provides a Lookup function for exactly this purpose.
Rob

Drag the item from the table where it's the Foreign Key, not it's native location.

Related

Inserting data from 1st table to 2nd table in different locations

In foxpro, I can simply do this to add or merge table with different locations:
-> use C:\tableA
-> append from D:\tableB
in this foxpro code I've provided, tableB which exists from location D:\ appends all its row into tableA.
The question now is, how do I do that in C#?
I can simply invoke this query: insert into tableA select * from tableB to append all rows from tableB to tableA. But this is only true when I used same database and their file location remained intact and same at the same time.
My problem is that the database location of these two tables were different. How do I resolve this problem using C#?
looking to linq statements. What kind of database is this? http://social.msdn.microsoft.com/Forums/en-US/172b4f22-8c6e-4186-9ff4-e593fbda7566/can-i-use-linq-or-sqlstatements-to-transfer-values-from-one-table-to-another?forum=lightswitchgeneral

Natural Join of two DataTables in C#

I have a DataSet that contains two tables. One is considered to be nested in the other.. All I want is for it to not be nested and for there to be one table. .Merge() and LINQ just aren't doing the trick.
Here is a sample of what the main table would look like
student-id ID
--------------------
123456789 1
654987321 2
But each of these has multiple rows that they correspond to in the next table
ID Col1 Col2 etc.
----------------------
1 fact1 fact2
1 fact3 fact4
2 fact5 fact6
I want to combine them so they would look like this...
student-id Col1 Col2
-------------------------------
123456789 fact1 fact2
123456789 fact3 fact4
654987321 fact5 fact6
Everytime that I try the merge it doesn't work I get an error that I cant duplicate the primary key which is "ID" and since the merge is based on the primary key(i believe) I cant remove it.
I cant use LINQ because I want to make this generic so that the second table could have any number of columns and I cant get the select to work for that.
UPDATE: MY SOLUTION
I ended up cloning the second table to a new data table. Then adding a column called 'student-id' and deleting the ID column. The I looped through the rows of the Main table finding and related them to row in the second table... Combined all the data in an array and created a row in the final table.
The LINQ isn't as bad as you suggest. You can just use an anonymous type that holds two DataRows:
var result = from t1 in table1.AsEnumerable()
join t2 in table2.AsEnumerable() on (int)t1["ID"] equals (int)t2["ID"]
select new
{
Student = t1,
Facts = t2
};
foreach(var s in result)
Console.WriteLine("{0} {1} {2}", s.Student["student-id"], s.Facts["Col1"], s.Facts["Col2"]);
That way, you're not including specific columns in your output, so you can access them after the fact.
That being said, the other poster's suggestion of using a pivot table is probably a better direction to go.
let's try it in SQL.
Let, 1st Table = Table1 and 2nd Table = Table2
SQL:
Select
X.student-id,Y.Col1,Y.Col2
From Table1 As X Inner Join Table2 As Y On Y.ID=X.ID
I think if you try it in SQL it's easy to do!!!
Sounds like what you need is a Pivot table.
This will essentially allow you to display the data how you want.
Here are a couple of tutorials/projects
http://www.codeproject.com/Articles/25167/Simple-Advanced-Pivots-with-C-and-ASP-NET
http://www.codeproject.com/Articles/46486/Pivoting-DataTable-Simplified
Update
you may find yourself better doing the 'pivot' part in MS SQL as stored procedure and then populating your datatable with the results of calling this stored procedure. This example here is a great starting block
http://blogs.msdn.com/b/spike/archive/2009/03/03/pivot-tables-in-sql-server-a-simple-sample.aspx

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

Importing CSV data into application DB maintaining foreign key consistence

In my ASP.NET web app I'm trying to implement an import/export procedure to save or insert data in the application DB. My procedure generates some CSV files: one for each table.
Obviously there are relations between some of these tables and when I import CSV in my DB I'd like to maintain association between rows.
Say I have Table1 and Table2 with Table2 that has a foreign key to Table1. So I could have a row in Table1 with ID = 100 and a row in Table2 with Table1_ID = 100.
When I import CSV with Table1 data, new IDs are generated for Table1 rows, how can I maintain consistency of the foreign keys in Table2 when I import the corresponding CSV file?
I'm using Linq-to-SQL to retrieve data from DB... using DataSet and DataTable can help me?
NOTE I'd like to permit cumulative import, so when I import a CSV file there may already be data in the DB. So I cannot use 'Set Identity OFF'.
Add the items of Table1 first, so when you add the items of Table2 there are the corresponding records of Table1 already in the database. For more tables you will have figure out the order. If you are creating a system of arbitrary database schema, you will want to create a table graph (where each node is a table and each arc is a foreign key) in memory [There are no types for that in the base library] and then convert it to a tree such that you get the correct order by traversing the tree (breadth-first).
You can let the database handle the cases where there is a violation of the foreign key, because there is not such field. You will have to decide if you make a transaction of the whole import operation, or per item.
Although analisying the CSVs before hand is possible. To do that, you will want to store the values for the primary key of each table [Use a set for that] (again, iterate over the tables in the correct order), and then when you are reading a table that has a foreign key to a table that you have already read you can check if the key is there, also it will help you yo detect any possible duplicate. [If you have things already in the database to take into account, you would have to query too... although, take care if the database is in an active system where records could be deleted while you are still deciding if you can add the CSVs without problem].
To address that you are generating new IDs when you add...
The simplest solution that I can think of is: don't. In particular if it is an active system, where other requests are being processed, because then there is no way to predict the new IDs before hand. Your best bet would be to add them one by one, in that case, you will have to think your transaction strategy accordningly... it may be the case that you will not be able to roll back.
Although, I think your question is a bit deeper: If the ID of the Table1 did change, then how can I update the corresponding records in the Table2 so they point to the correct record in Table1?
To do that, I want to suggest to do the analysis as I described above, then you will have a group of sets that will works as indexes. This will help you locate the records that you need to update in Table2 for each ID in Table1. [It is also important to keep track if you have already updated a record, and don't do it twice, because it may happen the generated ID match an ID that is yet to be sent to the database].
To roll back, you can also use those sets, as they will end up having the new IDs that identify the records that you will have to pull out of the database if you want to abort the operation.
Edit: those sets (I recommend hashset) are only have the story, because they only have the primary key (for intance: ID in Table1). You will need bags to keep the foreing keys (in this case Table1_ID in Table2).

SQL: Joining tables on primary key AND returning the primary key

I'm writing a C# application and am using an Access .mdb. I have a table with email messages and a table with message relations (each email msg can be assigned to several teams of workers), so the rows in the relations table have "msgId" and "teamName" fields.
I want to to get all messages from the first table which are assigned to a specified team. I'm using the following query:
"SELECT * FROM Mails INNER JOIN MailAssignments ON Mails.msgId = MailAssignments.msgId"
But it doesn't return the msgId for me, I guess, because the tables are joined on this field, but then I
m not able to identify messages in my C# code.
How can I make the query return the msgId for me?
It is enough specify the fields name in the selection, or add the table name where you want to get all the fields, try with this selection list :
SELECT Mails.*
FROM Mails INNER JOIN MailAssignments
ON Mails.msgId = MailAssignments.msgId
It should appear twice in the resultset, for Mails.msgId and MailAssignments.msgId respectively. However, you should not expect two columns named msgId. Rather, the DBMS should disambiguate the columns. This is a requirement of Standards SQL, BTW.
IIRC Access will rename both columns in order to disambiguate them. This would explain why there is no column named msgId in the result.

Categories