如果您使用SQL Server 2008或更高版本,可以使用table-valued parameters。這些讓你繼續處理上不同的行單獨的ID,執行SQL連接,等等有很多的網頁,我掛,例如在例子:
Using connection
' Create a DataTable with the modified rows.
Dim addedCategories As DataTable = _
CategoriesDataTable.GetChanges(DataRowState.Added)
' Define the INSERT-SELECT statement.
Dim sqlInsert As String = _
"INSERT INTO dbo.Categories (CategoryID, CategoryName)" _
& " SELECT nc.CategoryID, nc.CategoryName" _
& " FROM @tvpNewCategories AS nc;"
' Configure the command and parameter.
Dim insertCommand As New SqlCommand(sqlInsert, connection)
Dim tvpParam As SqlParameter = _
insertCommand.Parameters.AddWithValue(_
"@tvpNewCategories", addedCategories)
tvpParam.SqlDbType = SqlDbType.Structured
tvpParam.TypeName = "dbo.CategoryTableType"
' Execute the query
insertCommand.ExecuteNonQuery()
End Using
你可以很容易地替換INSERT
與UPDATE
,如前面頁面上顯示:
UPDATE dbo.Categories
SET Categories.CategoryName = ec.CategoryName
FROM dbo.Categories INNER JOIN @tvpEditedCategories AS ec
ON dbo.Categories.CategoryID = ec.CategoryID;
並相應地調整參數名稱。
啊哈,我還沒有用最新版本的SQL Server使用ADO.NET,聽起來不錯 – Tasio 2011-06-08 07:11:52
我使用的是2005年。 – dpp 2011-06-08 07:41:35
@domanokz - 在文章頂部有一系列關於如何做到這一點的建議之前的版本。最好的建議(如果它是一個「無限」數量的ID傳遞)可能會把它們放入XML並通過。 – 2011-06-08 07:53:26