我想從Access表中將變量/參數傳遞到SQL Server中的存儲過程,使用ADODB連接。我拉動Access和Access訪問查詢中的變量(所以我試圖傳遞每次執行代碼時更新的變量)。嘗試在Access VBA代碼中傳遞下面的變量時出現以下錯誤消息:將參數從訪問變量傳遞到SQL Server存儲過程
參數對象定義不正確。提供了不一致或不完整的信息。
我是新來的這種編碼。有人可以請提供一些指導如何將變量(Access查詢的結果)傳遞給存儲過程,然後在存儲過程中調用這些變量?
訪問VBA代碼:
'''CREATE LINKED TABLE THAT PULLS FROM TBL_STATEMENT_MASTER IN SQL
''variables to pass to get dFileRE
'' (1) stateDate
stateDate = getItem("select distinct paydate from update_statement_master_re")
'' (2) stateNGN
stateNGN = getItem("select distinct deal_code from update_statement_master_re")
user = GetUser()
'' Connect to Data Source - Securities DB - SQL Server
Set dbconn = New ADODB.Connection
dbconn.ConnectionString = "driver=SQL Server;server=R7SQL1;database=SecuritiesDB;trusted_connection=YES"
dbconn.Open dbconn.ConnectionString
Set cmd = New ADODB.Command
cmd.ActiveConnection = dbconn
'' Set CommandText equal to the stored procedure name (spStatementCheck)
cmd.CommandType = adCmdStoredProc
cmd.CommandText = "spStatementCheck"
cmd.NamedParameters = True 'paramStatementCheck'
'' THIS IS THE PART OF THE CODE THAT IS CRASHING – I AM NOT SURE HOW TO CALL THESE VARIABLES
cmd.Parameters.Append _
cmd.CreateParameter("@SPstateNGN", adVarChar, adParamInput, 0, "& stateNGN &")
cmd.Parameters.Append _
cmd.CreateParameter("@SPstateDate", adDate, adParamInput, 0, "& stateDate &")
SQL Server存儲過程的代碼:
USE [SecuritiesDB_TEST]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER PROCEDURE [dbo].[spStatementCheck]
@SPstateNGN as nvarchar(25),
@SPstateDate as datetime
AS
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
SET NOCOUNT ON;
-- Insert statements for procedure here
INSERT INTO UPDATE_Statement_Master_Check (NGN_Full, [Date], [DESCRIPTION], AMOUNT, NGN_SHORT, Series, FileDate, EffectiveDate, ActualDate, [Source], ID)
SELECT tbl_Statement_Master.NGN_Full, tbl_Statement_Master.[Date],
tbl_Statement_Master.[DESCRIPTION],
tbl_Statement_Master.AMOUNT,
tbl_Statement_Master.NGN_SHORT,
tbl_Statement_Master.Series,
tbl_Statement_Master.FileDate,
tbl_Statement_Master.EffectiveDate,
tbl_Statement_Master.ActualDate,
tbl_Statement_Master.[Source],
tbl_Statement_Master.ID
FROM tbl_Statement_Master
where tbl_Statement_Master.[Date] <> @SPstateDate
and tbl_Statement_Master.NGN_Full = @SPstateNGN
and tbl_statement_master.FileDate = (Select distinct max(filedate) from tbl_statement_master
where [DATE] = @SPstateDate and NGN_Full = @SPstateNGN);
我可能會在這裏丟失一些東西,但是'GetItem'行會返回多個值,並且您試圖將這些多個值傳遞給'CreateParameter'調用。難道你不希望在那裏有一個循環來遍歷每條記錄,並根據該記錄中的參數值執行存儲過程。 我不明白創建參數的''&&stateNGN&''部分。在過去,我只是將變量放在該參數中,而沒有引號或符號。 –
** GetItem **將只返回一個值。我使用了** stateNGN **和** stateDate **,因爲每次代碼執行時都需要更新這些變量,而不是對變量進行硬編碼。 – user2989011
「GetItem」指向的第二點是關於CreateParameter(「@ SPstateNGN」,adVarChar,adParamInput,0,stateNGN)',只是刪除引號和&符號,因爲變量中保存的任何值都作爲參數值。 –