我试图弄清楚如何为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)
本质上,我需要能够循环,直到每个客户都有一个数据表导出。
希望有意义,任何帮助都非常感激。
答案 0 :(得分:2)
这是一些未经测试的代码。但它会让你对我所谈论的内容有一个公平的想法(在问题的评论中)。
Sub Whatever()
connection.ConnectionString = "server=***01\SQLEXPRESS; database=Billing; integrated security=yes"
connection.Open()
Using da As New SqlDataAdapter("Select * FROM [Billing] ORDER BY Customer", connection)
da.Fill(datatableMain)
End Using
connection.Close()
' get distinct customers
Dim dv As New DataView(datatableMain)
Dim distinctCustomers As DataTable = dv.ToTable(True, "Customer")
For Each customer As DataRow In distinctCustomers.Rows
' this messagebox is only to give you an idea which customer you are printing
' not required in actual code.
MessageBox.Show("Exporting Customer... " & customer("Customer").ToString)
Dim customerRows() As DataRow = datatableMain.Select("Customer=" & customer("Customer").ToString) '<-- put single quotes around value if "Customer" field is of string type. e.g. "Customer='value'"
For Each customerRow As DataRow In customerRows
' all the rows related to this customer are here
' do whatever you do to export
Next
Next
End Sub