Sql server 循环运行非常慢

Sql server 循环运行非常慢,sql-server,vb.net,gridview,loops,Sql Server,Vb.net,Gridview,Loops,请帮我让我的应用程序快一点,现在循环并给我结果要花很长时间 以下是我所做的: 1.从上传的excel文件加载gridview这可能是大约300条记录 2.将制造商、型号和序列号与我的MS SQL数据库中大约20K条记录进行比较,以查看是否存在匹配项 'find source ID based on make/model/serial No combination. Dim cSource As New clsSource() Dim ds As DataSet =

请帮我让我的应用程序快一点,现在循环并给我结果要花很长时间

以下是我所做的: 1.从上传的excel文件加载gridview这可能是大约300条记录 2.将制造商、型号和序列号与我的MS SQL数据库中大约20K条记录进行比较,以查看是否存在匹配项

'find source ID based on make/model/serial No combination.
        Dim cSource As New clsSource()
        Dim ds As DataSet = cSource.GetSources()
        Dim found As Boolean = False

        'populate db datatables
        Dim dt As DataTable = ds.Tables(0)
        Dim rows As Integer = gwResults.Rows.Count()
        For Each row As GridViewRow In gwResults.Rows
            'move through rows and check data in each row against the dataset
            '1 - make
            For Each dataRow As DataRow In dt.Rows
                found = False
                If dataRow("manufacturerName") = row.Cells(1).Text Then
                    If dataRow("modelName") = row.Cells(2).Text Then
                        If dataRow("serialNo") = row.Cells(3).Text Then
                            found = True
                        End If
                    End If
                End If

                'display results
                If found Then
                    lblResults.Text += row.Cells(1).Text & "/" & row.Cells(2).Text & "/" & row.Cells(3).Text & " found"
                Else
                    lblResults.Text += row.Cells(1).Text & "/" & row.Cells(2).Text & "/" & row.Cells(3).Text & " not found "
                End If

            Next
        Next

有没有更好的方法来找到两者之间的匹配?我快死了。

对于300个gridview行中的每一行,您都在遍历所有20k个数据行。这使得300*20k=600万次循环迭代。难怪你的循环速度慢-

我建议使用以下算法代替伪代码:

For Each gridviewrow
    Execute a SELECT statement on your DB with a WHERE clause that compares all three components
    If the SELECT statement returns a row
        --> found
    Else
        --> not found
    End If
Next
使用此解决方案,您只有300次循环迭代。在每个循环迭代中,对数据库进行选择。如果您已经正确地为数据库编制了索引,即,如果您在字段manufacturerName、modelName和serialNo上有一个复合索引,那么这个选择应该非常快—比遍历所有20k数据行快得多


从数学角度来看,这将使算法的时间复杂度从On*m降低到On*log m,n表示gridview中的行数,m表示数据库中的记录数。

Hmm。。。如何将电子表格中的数据加载到tempdb中的一个表中,然后编写一个select,以您希望的方式比较行?这样,所有的数据比较都在服务器端进行,您将能够利用SQL实例的所有功能。

而Heinzi的答案是正确的;在循环之前执行昂贵的SQL查询,并使用数据视图进行过滤,这样做可能更为有益,这样您就不会碰到数据库300次

Execute a SELECT statement on your DB 
For Each gridviewrow
    if my datagridview.Select(String.format("manufacturerName={0}", row.item("ManufacturerName"))
    If the dataview has a row
        --> found
    Else
        --> not found
    End If
Next

注意:我只比较了一个标准来说明这一点,您可以在这里对所有三个标准进行筛选

我认为在循环中使用sql不好?我要试试看!谢谢@克鲁姆:一如既往:这要看情况而定。当然,对内存中的数据表进行1次访问要比对数据库执行1次SQL快。但是访问一个数据表20k次可能比执行一个SQL慢得多。