473,386 Members | 1,763 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,386 software developers and data experts.

Using multiple tables from a database

Hi,
Im having problems writing a query statement to select different columns from different tables to display on an invoice i made on an excel file. The reason i have a problem is because im using c-sharp and coding is a bit complicated at first...if anyone has ran into this problem or may know how to solve it, i would love to hear ur input.
P.S.Im using visual studio 2005 in case the coding may differ

George
Nov 27 '07 #1
12 2465
If you are looking to "JOIN" data from different tables you can do this within your stored procedure.

Here is an Example:

Expand|Select|Wrap|Line Numbers
  1. CREATE PROCEDURE [User_GetDetails_ByID]
  2. (
  3. @UserID int
  4. )
  5. AS
  6. SELECT
  7. tblA.UserID,
  8. tblA.FavoriteColorID,
  9. tblB.ColorName,
  10. tblA.FirstName,
  11. tblA.LastName
  12. FROM
  13. Users tblA
  14. LEFT JOIN Colors tblB ON tblA.FavoriteColorID = tblB.ColorID
  15. WHERE
  16. tblA.UserID = @UserID
  17. GO
  18.  
Hope this helps, please let me know if you would like further explination of this solution.

- Aaron Sandoval
"remember: There's a thin line between good | Great..."
Nov 27 '07 #2
Plater
7,872 Expert 4TB
Hi,
Im having problems writing a query statement to select different columns from different tables to display on an invoice i made on an excel file. The reason i have a problem is because im using c-sharp and coding is a bit complicated at first...if anyone has ran into this problem or may know how to solve it, i would love to hear ur input.
P.S.Im using visual studio 2005 in case the coding may differ

George
You use SQL to query databases, not a programming language like C# or VBNET.
What are you using for your code?
Nov 27 '07 #3
You use SQL to query databases, not a programming language like C# or VBNET.
What are you using for your code?
Well I'ved tried inserting sql queries into the commands that are supposed to carry out the procedure like this for example:

SELECT GuestFirstName FROM Guest WHERE ToGuestInvoice > 0

But it gives errors on FROM and WHERE because it doesn't recognize it. If this behind code would work I wouldn't have any problems...maybe it has an assembly or something im missing but I doubt it. Maybe u can enlighten me...Would really appreciate it.

George
Nov 28 '07 #4

SELECT GuestFirstName FROM Guest WHERE ToGuestInvoice > 0

George
Post your code for this C# method and we may be able to look at the syntax to see if it's incorrect somewhere.
Nov 28 '07 #5
Go to Try...right there I'm really kinda lost on how to access rows from two tables in a database...so as later to display it on an outside file.

private void button2_Click(object sender, EventArgs e)
{
//Get configuration settings for the database conection
ResortApplication.conf configdb = new conf();
//this is creating the connection string
string xmldb = configdb.fnGetKeyConfig("xmldb");
//this is creating the database connection
SqlConnection dbConnection = new SqlConnection(xmldb);
//this is creating the database command
SqlCommand myCommand = new SqlCommand();
//this is declaring a transaction variable with sqltransaction which is a default type in .net
SqlTransaction myTrans;
//open connection
dbConnection.Open();
// Begin the transaction.
myTrans = dbConnection.BeginTransaction();
// Assign the connection property.
myCommand.Connection = dbConnection;
// Assign transaction object for a pending local transaction
myCommand.Transaction = myTrans;

try
{

var rows = from e in RESORT.Guest where e.ToGuestInvoice = true select e;
foreach( var e in rows )
{
string name = e.LastName;
int id = e.GuestID;
Console.WriteLine( id + ": " + name );
}

myCommand.ExecuteNonQuery(); //execute a non query
myTrans.Commit(); //commit your transaction
}
Nov 28 '07 #6
Plater
7,872 Expert 4TB
A transaction is ment to be of update/insert/delete (I believe) which can only be to one table.
If you are doing a query, you should just use the SqlCommand object.

Take a look at this article:
http://www.thescripts.com/forum/thread635615.html
Nov 28 '07 #7
A transaction is ment to be of update/insert/delete (I believe) which can only be to one table.
If you are doing a query, you should just use the SqlCommand object.

Take a look at this article:
http://www.thescripts.com/forum/thread635615.html
Hey thanks Plater...makes sense...so when i use only the sqlcommand object can i use like a join on the behind code for the specific button procedure?
Nov 28 '07 #8
Plater
7,872 Expert 4TB
Hey thanks Plater...makes sense...so when i use only the sqlcommand object can i use like a join on the behind code for the specific button procedure?
Aye, you can change the CommandText to any valid SQL statement.

For example:
Expand|Select|Wrap|Line Numbers
  1. string sqlq="";
  2. sqlq+=" SELECT ";
  3. sqlq+=" tblA.UserID, ";
  4. sqlq+=" tblA.FavoriteColorID, ";
  5. sqlq+=" tblB.ColorName, ";
  6. sqlq+=" tblA.FirstName, ";
  7. sqlq+=" tblA.LastName ";
  8. sqlq+=" FROM ";
  9. sqlq+=" Users tblA ";
  10. sqlq+=" LEFT JOIN Colors tblB ON tblA.FavoriteColorID = tblB.ColorID ";
  11. sqlq+=" WHERE ";
  12. sqlq+=" tblA.UserID = @UserID ";
  13. sqlCom.CommandText = sqlq;
  14. sqlCom.Parameters.Add("@UserID ", SqlDbType.Int).Value = 12345
  15.  
Nov 28 '07 #9
Kool, thanks. Appreciate your help!
Nov 28 '07 #10
If you are looking to "JOIN" data from different tables you can do this within your stored procedure.

Here is an Example:

Expand|Select|Wrap|Line Numbers
  1. CREATE PROCEDURE [User_GetDetails_ByID]
  2. (
  3. @UserID int
  4. )
  5. AS
  6. SELECT
  7. tblA.UserID,
  8. tblA.FavoriteColorID,
  9. tblB.ColorName,
  10. tblA.FirstName,
  11. tblA.LastName
  12. FROM
  13. Users tblA
  14. LEFT JOIN Colors tblB ON tblA.FavoriteColorID = tblB.ColorID
  15. WHERE
  16. tblA.UserID = @UserID
  17. GO
  18.  
Hope this helps, please let me know if you would like further explination of this solution.

- Aaron Sandoval
"remember: There's a thin line between good | Great..."
Yeah a little further explanation wouldnt' hurt...
Nov 28 '07 #11
To begin, there are many ways to accomplish this task. This "JOIN" feature in SQL is very useful and can be used in many instances to "SELECT" data from multiple tables. Here is a small example of how we would use a "JOIN" statement and how we would use it with our C# ASP.NET application.

For this example, we have created 1 SQL Stored Procedure, 1 ASP.NET 2.0 Page with C# Code Behind Page. We are using the Northwind Database that is found in any copy of SQL. We are going to bind the results (from dataset) to a GridView control on our page.


SQL STORED PROCEDURE
Expand|Select|Wrap|Line Numbers
  1. CREATE PROCEDURE [CustomerOrders_GetAll_ByCountry]
  2. (
  3. @Country nvarchar(15)
  4. )
  5. AS
  6. SELECT
  7. tblA.OrderID,
  8. tblB.ContactName,
  9. tblB.CompanyName,
  10. tblA.ShippedDate
  11. FROM
  12. Orders tblA
  13. LEFT JOIN Customers tblB ON tblA.CustomerID = tblB.CustomerID
  14. WHERE
  15. tblA.ShipCountry = @Country
  16. GO
  17.  
NOTE: I personally use "SQL Helper" class which can be found on Microsofts website when you download DAAB (Data Access Application Block) for 2.0. This is a very easy way for you to work with your database and use Stored Procedures in your code. Another great way would be to use strongly-typed datasets to access this data.

IMPORTANT: If you want to use this SQL Helper class don't forget to add it into the App_Code folder in your project.


ASP.NET 2.0 HTML CODE
Expand|Select|Wrap|Line Numbers
  1. <%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="Default" %>
  2.  
  3. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
  4. <html xmlns="http://www.w3.org/1999/xhtml" >
  5. <head id="Head1" runat="server">
  6. <title>GridView Example</title>
  7. </head>
  8. <body>
  9. <form id="form1" runat="server">
  10. <asp:ScriptManager ID="ScriptManager1" runat="server" />
  11. <div>
  12. <asp:GridView ID="GridView1" runat="server" CellPadding="4" ForeColor="#333333" GridLines="None" AllowPaging="True" PageSize="10" OnPageIndexChanging="GridView1_PageIndexChanging">
  13. <FooterStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" />
  14. <RowStyle BackColor="#F7F6F3" ForeColor="#333333" />
  15. <EditRowStyle BackColor="#999999" />
  16. <SelectedRowStyle BackColor="#E2DED6" Font-Bold="True" ForeColor="#333333" />
  17. <PagerStyle BackColor="#284775" ForeColor="White" HorizontalAlign="Center" />
  18. <HeaderStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" />
  19. <AlternatingRowStyle BackColor="White" ForeColor="#284775" />
  20. </asp:GridView>
  21. &nbsp;</div>
  22. </form>
  23. </body>
  24. </html>
  25.  

ASP.NET 2.0 C# CODE BEHIND PAGE
Expand|Select|Wrap|Line Numbers
  1. using System;
  2. using System.Data;
  3. using System.Configuration;
  4. using System.Collections;
  5. using System.Web;
  6. using System.Web.Security;
  7. using System.Web.UI;
  8. using System.Web.UI.WebControls;
  9. using System.Web.UI.WebControls.WebParts;
  10. using System.Web.UI.HtmlControls;
  11. // DON'T FORGET TO ADD THIS DataAccessLayer NAMESPACE SO YOU CAN USE THE SQLHelper CLASS
  12. using DataAccessLayer;
  13.  
  14. public partial class Default : System.Web.UI.Page
  15. {
  16. // OF COURSE THIS SHOULD BE IN YOUR WEB.CONFIG FILE & ENCRYPTED
  17. string conString = "Server=YourServerName;Database=Northwind;User ID=MyUserName;Password=MyUserPassword;";
  18.  
  19. protected void Page_Load(object sender, EventArgs e)
  20. {
  21. Bind_GridView1();
  22. }
  23.  
  24. public void Bind_GridView1()
  25. {
  26. // we are going to set the country equal to USA
  27. string country = "USA";
  28. DataSet ds = new DataSet();
  29. ds = SqlHelper.ExecuteDataset(conString, "CustomerOrders_GetAll_ByCountry", country);
  30. GridView1.DataSource = ds;
  31. GridView1.DataBind();
  32. // THIS WOULD BE ONE WAY YOU COULD IMPLIMENT THE FOREACH STATEMENT WITH THE RETURNED DATA
  33. foreach(DataRow aRow in ds.Tables[0].Rows)
  34. {
  35. Response.Write(aRow["ContactName"].ToString() + "<br />");
  36. }
  37. }
  38.  
  39. public void GridView1_PageIndexChanging(object sender, GridViewPageEventArgs e)
  40. {
  41. GridView1.PageIndex = e.NewPageIndex;
  42. Bind_GridView1();
  43. }
  44.  
  45. }
  46.  

CONCLUSION:
You can create a new ASP.NET 2.0 C# WebSite and add this code into a page called "Default.aspx". Don't forget to add in the stored procedure into your Northwind Database, so you can successfully run example.

I hope this code helps. You used the "foreach" loop statement in your code and in this Bind method it writes out the data on the page as well as binds to the gridview control.


- Aaron Sandoval
"remember: Greatness can easily be achieved, as long as you never stop wanting to learn from others..."
Nov 29 '07 #12
Thanks Aaron, your code really helped. Appreciate the assistance.
Nov 29 '07 #13

Sign in to post your reply or Sign up for a free account.

Similar topics

1
by: bdj | last post by:
Hello! Can anyone tell me where to read more about best practices about this: Should I put data in a seperate scheme for tables, packages in anoter schema and create a lot of users that have...
3
by: sridevi | last post by:
Hello How to export data from ms-access database to excel worksheet using ASP. mainly i need to export data to multiple worksheets. it is very urgent to us. i have a sample code which works...
1
by: E Arredondo | last post by:
Hi, I am about migrate from an old program database to MySql (Running under RH LINUX)and I'm wondering which is the best option to do : I currently have one file for each of my modules, (I'm...
3
by: Random Person | last post by:
Does anyone know how to use VBA to relink tables between two MS Access databases? We have two databases, one with VBA code and the other with data tables. The tables are referenced by linked...
6
by: Don Leverton | last post by:
Hi All, I've got a situation where I am developing an Access 97 app for a client, and am in the "beta testing" stage. I have split the app up, using the DB splitter, into front-end /back-end...
1
by: Daveyk0 | last post by:
Hello there, I have a front end database that I have recently made very many changes to to allow off-line use. I keep copies of the databases on my hard drive and link to them rather than the...
4
by: Dave Edwards | last post by:
I understand that I can fill a datagrid with multiple queries, but I cannot figure out how to fill a dataset with the same query but run against multiple SQL servers, the query , table structure...
7
by: Ryan | last post by:
Quite awile ago I posted to this newsgroup in regards to using Datasets in my VB 2005 application. About how many Datasets should be used.. a limit to the number of tables that should be included...
7
by: Pete | last post by:
I need to import multiple tab delimited files for which I do not have the formats. All files have column headers in the the line. The files must be dynamic. The only common value is that the...
0
by: David | last post by:
- Are there any peculiarities with using curs.executemany(...) vs. multiple How many times are you calling execute vs a single executemany? The python call overhead will add up for thousands of...
0
by: taylorcarr | last post by:
A Canon printer is a smart device known for being advanced, efficient, and reliable. It is designed for home, office, and hybrid workspace use and can also be used for a variety of purposes. However,...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: aa123db | last post by:
Variable and constants Use var or let for variables and const fror constants. Var foo ='bar'; Let foo ='bar';const baz ='bar'; Functions function $name$ ($parameters$) { } ...
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.