傳遞參數給具名命令
如同將命令的結果作為具名命令的 out 變數傳出一樣,參數化命令的參數也可作為 in 變數傳入至具名命令。
下列程式碼範例會嘗試從 Northwind 資料庫擷取 CustomerID 為 "ALKFI" 客戶所下的所有訂單。 在呼叫具名命令時,便會提供 CustomerID 的值。
Const DS = "MySqlServer"
Const DB = "Northwind"
Const DP = "SQLOLEDB"
Dim objConn As New ADODB.Connection
Dim objRs As New ADODB.Recordset
Dim objComm As New ADODB.Command
CommandText = "SELECT OrderID, OrderDate, " & _
"RequiredDate, ShippedDate " & _
"FROM Orders " & _
"WHERE CustomerID = ? " & _
"ORDER BY OrderID"
ConnectionString = "Provider=" & DP & _
";Data Source=" & DS & _
";Initial Catalog=" & DB & _
";Integrated Security=SSPI;"
' Connect to the data source.
objConn.Open ConnectionString
' Set a named command.
objComm.CommandText = CommandText
objComm.CommandType = adCmdText
objComm.Name = "GetOrdersOf"
Set objComm.ActiveConnection = objConn
' Call the named command, passing a CustomerID value
' as the input parameter.
' "ALFKI" is the required input parameter,
' objRs is the resultant output variable.
objConn.GetOrdersOf "ALKFI", objRs
' Display the result.
Debug.Print "All orders by ALFKI:"
Do While Not objRs.EOF
Debug.Print vbTab & objRs(0) & vbTab & objRs(1) & vbTab & _
objRs(2) & vbTab & objRs(3)
objRs.MoveNext
Loop
' Clean up.
objRs.Close
objConn.Close
Set objRs = Nothing
Set objConn = Nothing
Set objComm = Nothing
請注意,所有輸入參數必須在任何輸入變數之前,而且參數的資料類型必須相符或可轉換成對應欄位的資料類型。 下列陳述式-
objConn.GetOrdersOf 12345, objRs
-將會導致資料類型不符的錯誤,因為必要的輸入參數為 String 類型,而不是 Integer 類型。
下列呼叫-
objConn.GetOrdersOf "12345", objRs
-為有效,但會產生空白資料集,因為資料庫中沒有這類記錄。