2012-10-16 57 views
3

Microsoft's own documentation提供刪除記錄如下的例子:SqlDataAdapter.DeleteCommand()適用於AddWithValue(),但不適用於Add() - 爲什麼?

// Create the DeleteCommand. 
command = new SqlCommand(
    "DELETE FROM Customers WHERE CustomerID = @CustomerID", connection); 

// Add the parameters for the DeleteCommand. 
parameter = command.Parameters.Add(
    "@CustomerID", SqlDbType.NChar, 5, "CustomerID"); 
parameter.SourceVersion = DataRowVersion.Original; 

adapter.DeleteCommand = command; 

但是我的系統上它不工作(抱怨缺少@CustomerID)。相反,如果我更換

command.Parameters.Add("@CustomerID", SqlDbType.NChar, 5, "CustomerID"); 

以上

command.Parameters.AddWithValue("@CustomerID", 5); 

It works

爲什麼?

回答

5

在這一行:

command.Parameters.Add("@CustomerID", SqlDbType.NChar, 5, "CustomerID"); 

在這種過載,5指的是參數,而不是值的長度。如果您想添加該值,則必須添加以下內容:

command.Parameters["@CustomerID"].Value = "5"; 
相關問題