[英]'For each' loop based in SQL select statement
I am trying to figure out how to perform a 'For Each' loop for each distinct value returned from an SQL query. 我试图弄清楚如何对SQL查询返回的每个不同值执行“ For Each”循环。
Here is my pseudo code. 这是我的伪代码。
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)
In essence I need to be able to loop until I have a datatable per customer exported. 本质上,我需要能够循环播放,直到每个导出的客户都有一个数据表为止。
Hope that makes sense, any help greatly appreciated. 希望有道理,任何帮助将不胜感激。
Here is some untested code. 这是一些未经测试的代码。 But it will give you a fair idea about what I was talking about (in the comments of question).
但这可以使您对我在说什么(在问题的评论中)有一个清晰的认识。
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.