Stored Procedure using Parameters

2019-05-26 01:36发布

问题:

The Following code returns a stored procedure with a hard value coded. I need to allow 74 to change to whatever is selected from a combo box. Any help is greatly appreciated. I am using a pass through query in Access.

Private Sub ok_Click()
    Dim objConnection As New ADODB.Connection    
    Dim objCom As ADODB.Command
    Dim provStr As String

    Set objCom = New ADODB.Command

    objConnection.Provider = "sqloledb"

    provStr = "Data Source=**;" & "Initial Catalog=IKB_QA;User Id=**;Password=**;"

    objConnection.Open provStr

    With objCom
        .ActiveConnection = objConnection
        .CommandText = "dbo.ix_spc_planogram_match 74"
        .CommandType = adCmdStoredProc

        .Execute
    End With

End Sub

回答1:

You can use the command object's parameter fields for a neater approach:

With objCom          
    .ActiveConnection = objConnection          
    .CommandText = "dbo.ix_spc_planogram_match"          
    .CommandType = adCmdStoredProc            

    .Parameters.Refresh
    .Parameters(1).Value = ComboBox1.Value

    .Execute      
End With  


回答2:

The following code grabs parameter from form and executes the stored procedure.

Dim Cmd1 As ADODB.Command
Dim lngRecordsAffected As Long
Dim rs1 As ADODB.Recordset
Dim intRecordCount As Integer
'-----
Dim cnnTemp As ADODB.Connection
Set cnnTemp = New ADODB.Connection
cnnTemp.ConnectionString = "DRIVER=SQL Server;SERVER=***;" & _
"Trusted_Connection=No;UID=***;PWD=***;" & _
"Initial Catalog=IKB_QA;"
cnnTemp.ConnectionTimeout = 400
'Open Connection
cnnTemp.Open
Set Cmd1 = New ADODB.Command
Cmd1.ActiveConnection = cnnTemp

'---

With Cmd1
Dim localv As Integer
Dim inputv

localv = [Forms]![start]![Selection]![cat_code]
.CommandText = "dbo.ix_spc_planogram_match " & inputv
.CommandType = adCmdStoredProc
Set inputv = Cmd1.CreateParameter("@catcode", 3, 1, 10000, localv)
Cmd1.Parameters.Append inputv
Set rs1 = Nothing
Set rs1 = Cmd1.Execute

localv = 0
Do While Not rs1.EOF

Debug.Print rs1.Fields.Item("POG_DBKEY").Value = "POG_DBKEY"
Debug.Print rs1.Fields.Item("COMP_POG_DBKEY").Value = "COMP_POG_DBKEY"
Debug.Print rs1.Fields.Item("CURR_SKU_CNT").Value = "CURR_SKU_CNT"
Debug.Print rs1.Fields.Item("COMP_SKU_CNT").Value = "COMP_SKU_CNT"
Debug.Print rs1.Fields.Item("SKU_TOTAL").Value = "SKU_TOTAL"
Debug.Print rs1.Fields.Item("MATCHD").Value = "MATCHD"
localv = localv + 1

rs1.MoveNext
Loop
localv = localv

rs1.Close
Set rs1 = Nothing
Set rs1 = Nothing

End With
End Sub


回答3:

You can try this concatenation:

replace your statement:

.CommandText = "dbo.ix_spc_planogram_match 74"

with:

.CommandText = "dbo.ix_spc_planogram_match " & yourComboBox.Text

Assuming the combo box name is yourComboBox