473,587 Members | 2,548 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

How to select/get multiple items in SQL database table using the item's foreign keys.

JnrJnr
88 New Member
I have two SQL database tables. One contains various products(with unique primary keys) and the other contains information related to the products aswel as the product's foreign keys.

What I want to do is first get all the foreign keys(using SQL queries/select statements) and "store" them so that I can then, according to those foreign keys, get the actual product related to each foreign key.
My database is all fine but my problem is getting the products.

Here I get all the foreign keys from my table...

Expand|Select|Wrap|Line Numbers
  1. SqlCommand getProductKeys = new SqlCommand("select ProductKey from Ordered_Products where OrderKey = '" + cbxOrderNumber.SelectedItem + "' ", sqlcon);
  2.             SqlDataReader readProdKeys = getProductKeys.ExecuteReader();            
  3.             while (readProdKeys.Read())
  4.             {
  5.                 Key = readProdKeys["ProductKey"].ToString();
  6.                 foreach (var item in Key)
  7.                 {
  8.                   MessageBox.Show("Product Key " + item.ToString());   
  9.                 }
  10.  
  11.             }
Now that I have the foreign keys I cant seem to get it right to select(get) the products.
Here is the statement to get the products

Expand|Select|Wrap|Line Numbers
  1. SqlCommand getProducts = new SqlCommand("select Product from Products where ProductID = '" + Key + "' ", sqlcon);
  2.             LBproductsOrderHist.Items.Add(getProducts.ExecuteScalar());
What Iv'e tried
...Iv'e tried putting the getProducts command in the foreach statemant in the getProductKeys command but I get the exception of "The connection was not closed. The connection's current state is open"
(I know you have to close a connection after you are done with the command but I cant close the connection while I'm still bussy getting information in the SQL_dataReader)
Obviousely it looks like you can not have a SQLcommand in another SQLcommand if the first command has not closed.

My presumption
I know I have to (or can) use an array to "store" the foreign keys so that I can get the products using the getProducts command without any exceptions.

Any tips or help will be appreciated!
Sep 13 '10 #1
2 3577
Christian Binder
218 Recognized Expert New Member
I think the problem is, that you are querying the first result-set while you want to query another, so your SqlConnection is busy. I'd try to open a second connection for the inner query (products) which hopefully doesn't interfere with the outer query (ordered_produc ts).

But I think, it would be better to optimize your query, so it returns the products with one query using join.
e.g. like this
Expand|Select|Wrap|Line Numbers
  1. SELECT Products.Product 
  2.   FROM Products 
  3.   JOIN Ordered_Products
  4.     ON Products.ProductID = Ordered_Products.ProductKey
  5.   WHERE Ordered_Products.OrderKey = ... cbxOrderNumber.SelectedItem ...
  6.  
Sep 13 '10 #2
JnrJnr
88 New Member
Thank you Christian Binder for you reply.
Although I did also find a way to make it work which is a bit longer and takes a bit longer to run, I think opening a second connection for the inner query (products) was the quickest way to go.

Just for interest's sake, here's what I did...

Expand|Select|Wrap|Line Numbers
  1.  //GET QUANTITY
  2.             sqlcon.Open();
  3.             SqlCommand getQuantity = new SqlCommand("select Quantity from QuantityTable where OrderKey = '" + cbxOrderNumber.SelectedItem + "' ", sqlcon);
  4.             lblQuantityOrderHist.Text = getQuantity.ExecuteScalar().ToString();
  5.             sqlcon.Close();
  6.  
  7.             //GET PRODUCTS 
  8.  
  9.             //first get amount of items with the specific id
  10.             sqlcon.Open();
  11.             SqlCommand getKeysQuant = new SqlCommand("select count(ProductKey) as amount from Ordered_Products where OrderKey = '" + cbxOrderNumber.SelectedItem + "' ", sqlcon);
  12.             IndexCount = int.Parse(getKeysQuant.ExecuteScalar().ToString());
  13.             sqlcon.Close();
  14.  
  15.             int[] index = new int[IndexCount];
  16.             //put all items in array
  17.             for (int i = 0; i != IndexCount; )
  18.             {
  19.                 sqlcon.Open();
  20.                 SqlCommand getProductKeys = new SqlCommand("select ProductKey from Ordered_Products where OrderKey = '" + cbxOrderNumber.SelectedItem + "' ", sqlcon);
  21.                 SqlDataReader readProdKeys = getProductKeys.ExecuteReader();
  22.                 while (readProdKeys.Read())
  23.                 {
  24.                     index[i] = int.Parse(readProdKeys["ProductKey"].ToString());
  25.                     i++;
  26.                 }
  27.  
  28.                 sqlcon.Close();
  29.                 break;
  30.             }
  31.  
  32.             foreach (var item in index)
  33.             {
  34.                 sqlcon.Open();
  35.                 SqlCommand getProducts = new SqlCommand("select Product from Products where ProductID = '" + item + "' ", sqlcon);
  36.                 SqlDataReader readProducts = getProducts.ExecuteReader();
  37.                 while (readProducts.Read())
  38.                 {
  39.                     string product = readProducts["Product"].ToString();
  40.                     if (LBproductsOrderHist.Items.Contains(product))
  41.                     {
  42.  
  43.                     }
  44.                     else
  45.                     {
  46.                         LBproductsOrderHist.Items.Add(product);
  47.                     }
  48.  
  49.                 }
  50.                 sqlcon.Close();
  51.             }
Sep 14 '10 #3

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

Similar topics

2
1236
by: is_grizzly_adams | last post by:
I am working on a Bid, Bid Details data entry screen and have decisions to make on how to work with Grids/Datasets/Lookups and Templates. My table layouts are as follows: Bid Bid_ID, Company_ID, Bid_Date ... Bid_Item Bid_ID, Item_ID, Cost_Category_ID...
26
14104
by: pb648174 | last post by:
I have a table called BidItem which has another table called BidAddendum related to it by foreign key. I have another table called BidFolder which is related to both BidItem and BidAddendum, based on a column called RefId and one called Type, i.e. type 1 is a relationship to BidItem and type 2 is a relationship to BidAddendum. Is there any...
5
3327
by: Ross A. Finlayson | last post by:
Hi, I'm scratching together an Access database. The development box is Office 95, the deployment box Office 2003. So anyways I am griping about forms and global variables. Say for example I'm adding a customer. The Customer fields are mostly foreign keys that refer to primary keys in other tables, left join instead of junction tables...
9
3898
by: sonal | last post by:
Hi all, I hv started with python just recently... and have been assigned to make an utility which would be used for data validations... In short we take up various comma separated data files for eg: area.txt, school.txt, students.txt.... and so on (ok?!?) now, 1. area code used in the school.txt must be defined in the area.txt (Primary key...
0
1493
by: Carl Vondrick | last post by:
Hi everyone, I am having trouble wrapping my mind around the ActiveRecord pattern and foreign keys. I understand that for each table, there should be a class, and each row is is effectively an instance. But, my problem arises when I look at foreign keys and advanced relationships. For basic foreign keys, I can just automatically...
1
1934
by: Allen Browne | last post by:
In Access 2007, you can select multiple items in the Navigation Pane, via Shift+Click, Ctrl+Click, Shift+arrow keys, etc. You can also Shift+Del an object to delete it without confirmation (just like the Database window in previous versions.) *But*, when you Shift+Del, A2007 misinterprets the held-down Shift and selects *all* previous...
0
1688
by: OldStd | last post by:
Updating data using 2 data sets I am having some problems in updating the database using two datasets as suggested by someone. 1. Data is displayed in a data grid from a dataset generated using the IDE that pulls data from two tables using an . The idea is to display the associated with the field. Because an is used, the IDE couldn’t...
6
14289
by: ravichoudhari | last post by:
i came accross requirement of multiple foreign keys in a table referencing the same primary key another table. i created the table relations using the relations editor in access. even though i could have multiple foreign keys to a table access did allow the referential integrity. my database structure is table1 - students table table 2...
4
5593
by: qwedster | last post by:
Howdy folks! I am using stored procedure to see if a value exists in database table and return 0 if exists or else -1, in the following SQL queries. However how to check if a value (that is null) exists in database table and return 0 if exists or else -1 using stored procedure? Please help. USE GO IF EXISTS (SELECT name FROM...
2
14647
by: qwedster | last post by:
Folk! How to programattically check if null value exists in database table (using stored procedure)? I know it's possble in the Query Analyzer (see last SQL query batch statements)? But how can I pass null value as parameter to the database stored procedure programattically using C#? Although I can check for empty column (the...
0
8215
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. ...
0
8347
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 tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that...
1
7973
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For...
0
6626
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then...
1
5718
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes...
0
5394
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert...
0
3844
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in...
1
2358
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
1
1454
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

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.