为什么sqlParameter请求sourceColumn?

时间:2016-02-05 09:17:18

标签: sql sql-server database parameters sqlcommand

我正在检查Microsoft的sqlParameter example并且我正在尝试理解:

指定SourceColumn

的原因和好处是什么?

sql命令已指定目标列。

    command = New SqlCommand( _
        "INSERT INTO Customers (CustomerID, CompanyName) " & _
        "VALUES (@CustomerID, @CompanyName)", connection)

    command.Parameters.Add("@CustomerID", SqlDbType.NChar, 5, "CustomerID")
    command.Parameters.Add("@CompanyName", SqlDbType.NVarChar, 40, "CompanyName")

enter image description here

1 个答案:

答案 0 :(得分:2)

在此实例中指定SourceColumn表示在DataColumn.ColumnNameDataTable中指定列名属性(Dataset)。只有当您将SqlDataAdapter对象与SqlCommand一起使用时,这一点非常重要:

--first, fill a DataTable with data from the database:
Dim dt As New DataTable
Dim cmdSelect = New SqlCommand("SELECT CustomerID, CompanyName FROM Customers;", connection)
Dim daCustomers As New SqlDataAdapter
daCustomers.SelectCommand = cmdSelect
daCustomers.Fill(dt)

--Now our DataTable has two columns: "CustomerID" and "CompanyName"
--We can help out our DataAdapter by telling it which columns in the database
--correspond with which columns in the DataTable 
--which is what you've done with your fourth argument of .Parameters.Add()
command = New SqlCommand( _
    "INSERT INTO Customers (CustomerID, CompanyName) " & _
    "VALUES (@CustomerID, @CompanyName)", connection)

command.Parameters.Add("@CustomerID", SqlDbType.NChar, 5, "CustomerID")
command.Parameters.Add("@CompanyName", SqlDbType.NVarChar, 40, "CompanyName")
daCustomers.InsertCommand = command

如果我们这样做,那么我们就不必指定两个参数的值(在这种情况下,当InsertCommand触发时),因为数据适配器只会查看适当的DataColumn&中的值致电DataRow时会自动daCustomers.Update(dt)

同样,如果您希望SqlDataAdapter更有用,您还需要为定义的SourceColumnUpdateCommand s的参数指定DeleteCommand 。请注意,很多人更喜欢使用SqlCommandBuilder object to automatically configure他们的SqlDataAdapters这个和其他简单的适配器而没有为他们的SqlCommand对象指定任何东西,但我更喜欢这个除了最简单的情况外,对任何事情都采取更明确的方法。

当您<{>>未使用 SourceColumn与您的SqlDataAdapter时,指定SqlCommand时,我不知道可以获得任何好处。