473,414 Members | 1,876 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,414 software developers and data experts.

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

JnrJnr
88
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

✓ answered by Christian Binder

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_products).

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.  

2 3551
Christian Binder
218 Expert 100+
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_products).

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
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
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,...
26
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...
5
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...
9
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...
0
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...
1
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...
0
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...
6
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...
4
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...
2
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...
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
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,...
0
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...
0
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...
0
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,...
0
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...
0
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...

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.