2011-06-08 106 views
0

我正在使用Windows窗體 - VB.NET。SQL Server - 基於列表更新行

這是我有:

  • 一個ListView設置爲True
  • 複選框一個Button(觸發更新)
  • 類似領域的ListView

數據庫表我想要發生的事情:

  • 當用戶點擊Button時,ListView勾選複選框的所有項目都會被更新。

我的進步:

  • 我已經收集到的檢查的項目的ID並將其存儲在數組中。我將使用它來更新數據庫表。

問題:

  • 我不知道如何把他們在SqlCommand.Parameters
  • 另外,我不知道這樣的場景更新命令(其中/存在(@參數))

在此先感謝!

回答

1

如果您使用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 

你可以很容易地替換INSERTUPDATE,如前面頁面上顯示:

UPDATE dbo.Categories 
SET Categories.CategoryName = ec.CategoryName 
FROM dbo.Categories INNER JOIN @tvpEditedCategories AS ec 
ON dbo.Categories.CategoryID = ec.CategoryID; 

並相應地調整參數名稱。

+0

啊哈,我還沒有用最新版本的SQL Server使用ADO.NET,聽起來不錯 – Tasio 2011-06-08 07:11:52

+0

我使用的是2005年。 – dpp 2011-06-08 07:41:35

+0

@domanokz - 在文章頂部有一系列關於如何做到這一點的建議之前的版本。最好的建議(如果它是一個「無限」數量的ID傳遞)可能會把它們放入XML並通過。 – 2011-06-08 07:53:26

0

看來你想使用一個單一的調用數據庫,因爲你需要用命令建立一個字符串,我不認爲你可以將一個列表作爲參數傳遞給一個命令/ sp。

update命令:

UPDATE [table] SET [field1] = value1, [field2] = value2 
WHERE [ID] IN (id1, id2, ..., idN) 
+0

是嗎?在哪裏()?啊,另一個問題,我該如何通過SqlCommand.SqlParameter傳遞id的ID? – dpp 2011-06-08 06:56:56

+0

我不認爲你可以通過SqlParameter傳遞一個列表,如果你想使用一個命令,你必須建立你的字符串與WHERE IN和你得到的列表。 – Tasio 2011-06-08 07:10:41