【发布时间】:2014-10-18 13:00:09
【问题描述】:
我试图弄清楚如何为 SQL 查询返回的每个不同值执行“For Each”循环。
这是我的伪代码。
connection.ConnectionString = "server=***01\SQLEXPRESS; database=Billing; integrated security=yes"
command.Connection = connection
command.CommandType = CommandType.Text
command.CommandText = "SELECT DISTINCT [Customer] FROM [Billing]
For Each... Distinct value returned above
command.CommandType = CommandType2.Text
command.CommandText2 = "Select * FROM [Billing] WHERE [Customer] = [DISTINCT VALUE FROM ABOVE]
dataAdapter.SelectCommand = command
'Fill data to datatable
connection.Open()
dataAdapter.Fill(datatableMain)
connection.Close()
Then Export (I am ok with the Export code)
本质上,我需要能够循环,直到我为每个客户导出了一个数据表。
希望这是有道理的,非常感谢任何帮助。
【问题讨论】:
-
那是真实的代码吗?为什么您要循环每个不同的客户只是为了能够为这些客户选择所有比林斯?首先选择所有账单不是更有效吗?
Select * FROM [Billing] ORDER BY Customer -
您可以在 Billing 表和 Group By Customer 上使用自联接。
-
@PradeepKumar:假设他不想要每个客户的所有行。内部选择反对。
-
我需要为每个客户提供单独的输出。所以对于客户 A,我想导出一个包含客户 A 的所有账单明细的文件,对于客户 B,我想导出所有客户 B 的账单明细等等......
-
ok.. 在这种情况下,您只需填写一次数据表 (
SELECT * FROM Billing ORDER BY Customer)。然后,您可以过滤每个客户并获取与该客户相关的行。这比分别为每个客户循环和填充数据要高效得多。
标签: sql vb.net for-loop foreach