【发布时间】:2018-08-26 22:07:11
【问题描述】:
我在SQL Server 中有以下table,称为tblProducts:
+-----------+--------------+-------------+
| pkProduct | fkProductID | intIssue |
+-----------+--------------+-------------+
| 1 | 10 | 1 |
| 2 | 10 | 2 |
| 3 | 10 | 4 |
| 4 | 11 | 1 |
| 5 | 11 | 2 |
| 6 | 11 | 3 |
| 7 | 11 | 5 |
| 8 | 12 | 1 |
| 9 | 13 | 1 |
| 10 | 13 | 4 |
| 11 | 14 | 1 |
| 12 | 14 | 3 |
| 13 | 14 | 6 |
| 14 | 15 | 1 |
| 15 | 16 | 1 |
+-----------+--------------+-------------+
随着时间的推移,无论出于何种原因,行已被删除,问题编号现在存在差距。我希望问题编号按顺序运行,以便 table 看起来像这样:
+-----------+--------------+-------------+
| pkProduct | fkProductID | intIssue |
+-----------+--------------+-------------+
| 1 | 10 | 1 |
| 2 | 10 | 2 |
| 3 | 10 | 3 |
| 4 | 11 | 1 |
| 5 | 11 | 2 |
| 6 | 11 | 3 |
| 7 | 11 | 4 |
| 8 | 12 | 1 |
| 9 | 13 | 1 |
| 10 | 13 | 2 |
| 11 | 14 | 1 |
| 12 | 14 | 2 |
| 13 | 14 | 3 |
| 14 | 15 | 1 |
| 15 | 16 | 1 |
+-----------+--------------+-------------+
目前我已将table 添加到我的DataSet 并在vb.net 代码中使用它来更新行:
Dim currentProductsTable As tblProductsDataTable
Using taProduct As New tblProductsTableAdapter
currentProductsTable = taProduct.GetData
End Using
Dim issueCounter As Integer = 1
Dim previousRow As tblProductsRow = Nothing
Using con As SqlConnection = New SqlConnection(My.Settings.MyConnectionString)
Using cmd As New SqlCommand("UPDATE dbo.tblProducts SET [intIssue] = @issueCounter WHERE pkProduct = @ProductID", con)
cmd.Connection = con
con.Open()
For Each row As tblProductsRow In currentProductsTable.Rows
If Not previousRow Is Nothing Then
If row.fkProductID = previousRow.fkProductID Then
cmd.Parameters.Clear()
cmd.Parameters.Add("@issueCounter", SqlDbType.Int).Value = issueCounter
cmd.Parameters.Add("@ProductID", SqlDbType.Int).Value = row.pkProduct
previousRow = row
Else
issueCounter = 1
cmd.Parameters.Clear()
cmd.Parameters.Add("@issueCounter", SqlDbType.Int).Value = issueCounter
cmd.Parameters.Add("@ProductID", SqlDbType.Int).Value = row.pkProduct
previousRow = row
End If
Else
issueCounter = 1
cmd.Parameters.Clear()
cmd.Parameters.Add("@issueCounter", SqlDbType.Int).Value = issueCounter
cmd.Parameters.Add("@ProductID", SqlDbType.Int).Value = row.pkProduct
previousRow = row
End If
cmd.ExecuteNonQuery()
issueCounter += 1
Next
End Using
End Using
我已通过fkProductID ASC 和intIssue ASC 订购了.GetData,
但是这需要很长时间,因为table 中有大约 30000 个rows。
我想知道是否有更快的方法来进行这种更新?
【问题讨论】:
-
用您正在使用的数据库标记您的问题。
-
已标记,真是个沃利!对不起。
标签: sql sql-server vb.net foreach sql-update