Dim rst As New ADODB.Recordset
rst.Open "SELECT * FROM dbo.ftblTest(1,2,3)", CP.Connection, adOpenKeyset, adLockReadOnly
但是這將是更好的做到這一點:
rst.Open "SELECT * FROM dbo.ftblTest(@Param1=1,@Param2=2,@Param3=3)", CP.Connection, adOpenKeyset, adLockReadOnly
如果我嘗試第二種方法我得到的錯誤:「參數未提供功能ftblTest」
是否有可能使用具有多語句表值函數的命名參數?
編輯1:實施例中加入使用Command對象
首先SQL
create function ftblTest (@Input int)
RETURNS @Results TABLE (
OutputField int
)
AS
BEGIN
INSERT INTO @Results SELECT @Input
Return
End
一些代碼(從Access 2003 ADP內運行,以正確的SQL連接DB)
Public Sub test()
Dim rst As New ADODB.Recordset
Dim cmd As New ADODB.Command
'method 1 works
rst.Open "SELECT * FROM dbo.ftblTest(2)", CurrentProject.Connection, adOpenKeyset, adLockReadOnly
Debug.Print rst.Fields(0)
rst.Close
With cmd
.ActiveConnection = CurrentProject.Connection
.CommandType = adCmdTable
'method 2 works
.CommandText = "dbo.ftblTest(3)"
Set rst = cmd.Execute
Debug.Print rst.Fields(0)
'method 3 fails
.CreateParameter "@Input", adInteger, adParamInput, , 4
.CommandText = "dbo.ftblTest(@Input)"
Set rst = cmd.Execute 'error here:-2147217900 Must declare the scalar variable "@Input".
Debug.Print rst.Fields(0)
End With
End Sub
我該怎麼辦獲取命名參數在方法3中工作?
編輯2:測試代碼修改爲使用Parameters.Append
Public Sub test()
Dim rst As New ADODB.Recordset
Dim cmd As New ADODB.Command
Dim p As New ADODB.Parameter
With cmd
.ActiveConnection = CurrentProject.Connection
.CommandType = adCmdTable
'Parameter Append method fails
p = .CreateParameter("@Input", adInteger, adParamInput, , 4)
Debug.Print p.Name, p.Type = adInteger, p.Direction = adParamInput, p.SIZE, p.Value 'note that name not set!
With p
.Name = "@Input"
.Type = adInteger
.Direction = adParamInput
.SIZE = 4 'this shouldn't be needed
.Value = 4
End With
Debug.Print p.Name, p.Type = adInteger, p.Direction = adParamInput, p.SIZE, p.Value 'properties now set
.Parameters.Append p
.CommandText = "dbo.ftblTest(@Input)"
Set rst = cmd.Execute 'error here:-2147217900 Must declare the scalar variable "@Input".
Debug.Print rst.Fields(0)
End With
End Sub
這仍然無法正常工作。
編輯3:我刪除了@從創建參數
的建議,並試圖在CommandText 3種方式,得到了3個不同的錯誤:
.CommandText = "dbo.ftblTest"
錯誤:參數不爲函數提供'dbo.ftblTest'。
.CommandText = "dbo.ftblTest()"
錯誤:爲過程或函數dbo.ftblTest提供的參數數量不足。
.CommandText = "dbo.ftblTest(Input)"
錯誤:「輸入」不是公認的表格提示選項。如果它的目的是作爲表值函數或CHANGETABLE函數的參數,請確保將數據庫兼容模式設置爲90.
可能會感興趣:http://www.w3schools.com/ado/met_comm_createparameter.asp – Fionnuala 2010-07-27 09:26:06