[英]How to loop data from a table in sql server and using the returned data to query another table. Please see
This is what I am trying to achieve : 这是我要实现的目标:
I have a table in a database in which there is a column named "item_code". 我在数据库中有一个表,其中有一个名为“ item_code”的列。
I need to query this table, returning ONE row at a time. 我需要查询该表,一次返回一行。 Now, I need to use the value of the column "item_code" for the one row which has been returned to query ANOTHER table where I'll use it to fetch a bunch of row(s). 现在,我需要对返回到查询ANOTHER表的一行使用“ item_code”列的值,在这里我将使用它来获取一堆行。 How do I do this? 我该怎么做呢?
I tried using a datareader object in a while loop, fetch one row at a time and then query the other table inside this loop to fetch the rows required but I couldn't figure out how to put this data in a gridview (use datatable? if yes, how?) in such a way that the previous rows in the gridview don't get erased after each iteration of the while loop. 我尝试在while循环中使用datareader对象,一次获取一行,然后查询该循环内的另一张表以获取所需的行,但是我不知道如何将这些数据放入gridview中(使用datatable?如果是,怎么办?)的方式是,在while循环的每次迭代之后都不会擦除gridview中的前几行。
The only way I know for putting data into a gridview is by using .Fill() but obviously, Fill method wouldn't do in this case as it would wipe out the previous entries in the gridview. 我知道的将数据放入gridview的唯一方法是使用.Fill(),但是显然,在这种情况下Fill方法不会这样做,因为它将清除gridview中的先前条目。
Please help. 请帮忙。
I need to query this table, returning ONE row at a time. 我需要查询该表,一次返回一行。 Now, I need to use the value of the column "item_code" for the one row which has been returned to query ANOTHER table where I'll use it to fetch a bunch of row(s). 现在,我需要对返回到查询ANOTHER表的一行使用“ item_code”列的值,在这里我将使用它来获取一堆行。 How do I do this? 我该怎么做呢?
You could use a single SQL query that joins the two tables on "item_code" and retrieves the results from the second table. 您可以使用单个SQL查询将“ item_code”上的两个表连接起来,然后从第二个表中检索结果。
Your solution will work, but you are correct, Fill() will erase the contents of the table. 您的解决方案将起作用,但是您是正确的,Fill()将擦除表中的内容。 Instead, use Merge() 而是使用Merge()
var myMainTable = new DataTable();
foreach(var itemId in itemIds)
{
var currentTable = new DataTable();
// submit new query
myAdapter.Fill(currentTable)
myMainTable.Merge(currentTable);
}
You can make it in SQL level in one step, like this: 您可以一步一步将其设置为SQL级别,如下所示:
SELECT Table2.*
FROM Table2
INNER JOIN Table1 ON Table1.item_code = Table2.item_code
ORDER BY Table2.item_code
And of course if you need to make a smaller list, you can wirte the WHERE
too. 当然,如果您需要做一个较小的列表,也可以在WHERE
进行筛选。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.