VBscript can't get SQL stored procedure results - sql-server-2008

I created a proof-of-concept solution in one environment, but it isn't working in my test environment. My stored procedure works fine, as reported in SQL Management Studio and C#, and even in my development environment, but not in my test environment. Please help!
Here is some code to look at:
Function GetAutofillDatabaseInformation(docHandle, kwToCheck, autofillTableName, iDataType, aKeywordValues)
Dim i, adoParam, tempState, errDesc
GetAutofillDatabaseInformation = True
If Len(autofillTableName) = 0 Then autofillTableName = Null
On Error Resume Next
Set adoParam = adoCmd.CreateParameter("#Handle", adBigInt, adParamInput, , docHandle)
adoCmd.Parameters.Append(adoParam)
Set adoParam = adoCmd.CreateParameter("#KeyTypeNum", adBigInt, adParamInput, , kwToCheck)
adoCmd.Parameters.Append(adoParam)
Set adoParam = adoCmd.CreateParameter("#KeysetName", adChar, adParamInput, 200, autofillTableName)
adoCmd.Parameters.Append(adoParam)
Set adoParam = adoCmd.CreateParameter("#Datatype", adInteger, adParamOutput)
adoCmd.Parameters.Append(adoParam)
adoCmd.CommandType = adCmdStoredProc
adoCmd.CommandText = "usp_Check_Autofill_Value_Data"
adoCmd.ActiveConnection = adoConn
Set adoRs = adoCmd.Execute
tempState = adoRs.State
errDesc = err.description
On Error Goto 0
ReDim aKeywordValues(0)
If Len(errDesc) = 0 Then
i = 0
Do until adoRs.EOF
i = i + 1
ReDim preserve aKeywordValues(i)
aKeywordValues(i) = Trim(adoRs(0))
adoRs.MoveNext
Loop
adoRs.Close
iDataType = adoCmd.Parameters("#Datatype")
If err.number <> 0 Then
sErrMsg = "Cannot retrieve data information: " & err.description
GetAutofillDatabaseInformation = False
End If
Else
sErrMsg = "No information retrieved from database for document " & docHandle & ", keyword " & kwToCheck & " and autofill table [" & autofillTableName & "]."
GetAutofillDatabaseInformation = False
End If
End Function
I don't get any error message. The adoRs recordset object is always closed, and the #Datatype parameter doesn't get populated.
In my development environment, it all works fine. The development environment is Sql Server 2008 R2 SP1. The test environment is SP2 instead.
Is there some difference between SP1 and SP2 that would cause the ADO recordset not to be able to get any data?

Related

VBscript call stored procedure from MySQL with output parameters [duplicate]

This question already has answers here:
Using Stored Procedure in Classical ASP .. execute and get results
(3 answers)
Closed last year.
[ EDIT 20220219 ]
Resolved using VBSCRIPT CODE below
SQL = " CALL NewCheckData(#pOld); "
cn.execute(SQL)
SQL = " SELECT #pOld; "
Set RS = cn.execute(SQL)
pOld = cInt(RS("#pOld"))
[ EDIT 20220219 ]
[EDIT]
I have a Stored Procedure on a MySQL DB.
Which simply takes the COUNT ROWS of a Parameter and returns the Value of that Parameter.
I would like to call this Stored Procedure to assign value to variable in my VBscript code.
This is MySql routine (stored procedure) tried and worked.
CREATE DEFINER=`user`#`%` PROCEDURE `NewCheckData`(OUT pOld INT (11))
BEGIN
SELECT
COUNT(*) tOld INTO pOld
FROM
`DoTable`
WHERE
DATE( myDATE ) = CURRENT_DATE;
END
VBSCRIPT CODE is as below
On Error Resume Next
Const adCmdStoredProc = 4
Const adInteger = 3
Const adVarWChar = 202
Const adParamInput = &H0001
Const adParamOutput = &H0002
Const adParamReturnValue = &H0004
Set cn = CreateObject("ADODB.Connection")
cn.Open "DRIVER={MySQL ODBC 5.1 Driver};SERVER=XXX;PORT=3306;DATABASE=XXX;USER=XXX;PASSWORD=XXX;OPTION=3;"
cn.CommandTimeout = 10000
Set cmd = CreateObject("ADODB.Command")
With cmd
Set .ActiveConnection = cn
.CommandText = "NewCheckData"
.CommandType = adCmdStoredProc
.Parameters.Append .CreateParameter("RETURN_VALUE", adInteger, adParamReturnValue )
.Parameters.Append .CreateParameter("#pOld", adInteger, adParamOutput, 11)
.Execute
parmval = .Parameters(0).Value
End With
cn.Close()
Set cn = Nothing
If Err.Number <> 0 Then
WScript.Echo "Error in : " & Err.Description
Err.Clear
End If
On Error GoTo 0
Error or messagebox
Error or messagebox
Any suggestion, please.
[OLD QUESTION]
I am working with VBSCRIPT and using stored procedure MySQL.
I have to get the value of stored procedure out parameter.
This is MySql routine (stored procedure) tried and worked
CREATE DEFINER=`user`#`%` PROCEDURE `CheckData`(OUT pOld INT (11))
BEGIN
SELECT
COUNT(*) tOld INTO pOld
FROM
`DoTable`
WHERE
DATE( myDATE ) = CURRENT_DATE;
END
VBSCRIPT CODE is as below
Set cn = CreateObject("ADODB.Connection")
cn.Open "DRIVER={MySQL ODBC 5.1 Driver};SERVER=XXX;PORT=3306;DATABASE=XXX;USER=XXX;PASSWORD=XXX;OPTION=3;"
cn.CommandTimeout = 1000
Set objCommandSec = CreateObject("ADODB.Command")
objCommandSec.ActiveConnection = cn
objCommandSec.CommandType = 4
objCommandSec.CommandText = "CheckData"
objCommandSec.Parameters.Refresh
objCommandSec.Parameters.append objCommandSec.createParameter("#pOld", adInteger, adParamReturnValue) <<< error line
objCommandSec.execute , , adExecuteNoRecords
pOld = objCommandSec.Parameters("#pOld").value
MsgBox(pOld)
cn.Close()
Set cn = Nothing
Error or messagebox line 15
Error 'Arguments are of the wrong type, are out of acceptable range, or are in conflict with one another'
Any suggestion, please.
Edit: I failed to consider and mention that the below code example is accessing a MS-SQL DB. The behavior could therfor be different.
I don't use .VBS much anymore, but as I believe you are using the "Windows Script Host" environment I don't think it will make much difference. In the past I have done essentially the same thing as you demonstrate above many times with WSH & .JS. I also always ran into problems when I explicitly added the parameter definitions. I have since learned that for me the .refresh() is completely sufficient. I therefore leave .createParameter out now and simply give the named parameters the needed values as such:
var jsADO = {};
jsADO.objConn = new ActiveXObject("ADODB.Connection");
jsADO.objConn.Open("Provider=SQLOLEDB.1;...");
jsADO.cmd_insertShare = new ActiveXObject("ADODB.Command");
var cmd = jsADO.cmd_insertShare;
cmd.ActiveConnection = jsADO.objConn;
cmd.CommandType = adCmdStoredProc; // 4
cmd.CommandText = "usp_insertShare";
cmd.Prepared = true;
cmd.NamedParameters = true;
cmd.Parameters.Refresh()
...
var sqlRec;
var cmd = jsADO.cmd_insertShare;
cmd.Parameters("#p_Server") = "myServer";
cmd.Parameters("#p_Name") = "myShare";
cmd.Parameters("#p_Description") = "myShare Desc";
cmd.Parameters("#p_LocalPath") = "sharePath";
sqlRec = cmd.Execute(null, null, 0);
The syntax is indeed different, but I hope the gist is clear.
In summary, I think you've got it, just try leaving the .createParameter function out and only setting the named parameter values.

MySQL filter two field in recordset error on Update - VBA Excel - Run-time error '-2147467259 (80004005)'

I have a MySQL database from which I request a recordset of clients, and then I filter the recordset for a specific client based on two fields: 1) client code and 2) year applicable. I then assign values from a userform's objects to the MySQL fields, and update that specific client's records to the database.
I get the following error upon updating the table (running 'rstIT.Update'), and I think it has to do with the way I am implementing the filter:
Run-time error '-2147467259 (80004005)': [MySQL][ODBC 8.0(w)
Driver][mysqld-5.5.5-10.2.36-MariaDB-log-cll-lve]Build WHERE ->
insert_fields() failed
I am sure there must be an easier / more clever way to filter for the correct client, and update the records accordingly. Any help to resolve my current problem or another method would be greatly apppreciated!
Dim cn As ADODB.Connection
Dim rstIT As ADODB.recordSet
Dim rstClients As ADODB.recordSet
Dim Jaar As String
Jaar = cboTaxPeriod.Text
ITID = lblClientCode.Caption
Application.DisplayAlerts = False
Dim str As String
str = "DRIVER={MySQL ODBC 8.0 Unicode Driver};SERVER=myserveraddress;DATABASE=mydatabasename;PORT=myport;UID=user_"
str = str & LCase(LoggedInName)
str = str & ";PWD="
str = str & Password
str = str & ";FOUND_ROWS=1;"
Set cn = New ADODB.Connection
cn.ConnectionString = str
cn.Open
Set rstIT = New ADODB.recordSet
With rstIT
.Open "IT", cn, adOpenKeyset, adLockOptimistic, adCmdTable
End With
rstIT.Filter = "ClientCode = '" & ITID & "' AND TaxYear = '" & Jaar & "'"
If rstIT.EOF Then
MsgBox "Client code does not exist in tax table.", vbOKOnly, "Choose new client code"
GoTo GaanUit 'This closes everything and exits
Else
rstIT!TaxStatus.value = LTrim(RTrim(cboTaxStatus.Text))
rstIT!TaxStatusStaff.value = RTrim(LTrim(lblTaxStatusStaff.Caption))
If lblDueDate.Caption <> "" Then
lblDueDate.Caption = Format(lblDueDate.Caption, "yyyy-mm-dd")
rstIT!DueDate.value = lblDueDate.Caption
Else
rstIT!DueDate = Empty
End If
End If
rstIT.Update
My guess is, that code and year are numeric, thus no quotes:
rstIT.Filter = "ClientCode = " & ITID & " AND TaxYear = " & Jaar & ""

Access VBA: Recordset should be NOT nothing

I have a Front-End database setup for users to extract data regarding a list of information that they upload. The export function worked fine except they want the results to go to the open workbook add a sheet with the data without saving. The problem is that the created query has data when I run the query before or after the macro is not running. However as the macro is running the query returns nothing. The latest VBA I'm using is below. Please review and advise what I'm missing.
Thank you,
MS Office - Access: 2010
Active Reference Library:
Visual Basic for applications
Microsoft Access 14.0 Object Library
OLE Automation
Microsoft Excel 14.0 Object Library
Microsoft Office
14.0 Access database engine Object Library
Macro:
Private Sub ExpFile_Click()
Dim sql2export, s As String, blnExcel, blnWhere As Boolean, qdf As QueryDef, xlApp As Object, ws As Excel.Worksheet
Dim MyDatabase As DAO.Database, MyQueryDef As DAO.QueryDef, MyRecordset As DAO.Recordset
blnWhere = False
If Me. QueryASubform.Visible = True Then 'exceptions
sql2export = "QueryA"
blnWhere = True
ElseIf Me. QueryBSubform.Visible.Visible = True Then 'no Program Group for Build ID
sql2export = " QueryB"
ElseIf Me. QueryCSubform.Visible = True Then 'Bill to and Type report.
sql2export = " QueryC"
Else: Exit Sub
End If
If blnWhere = False Then
s = "select * from " & sql2export & " Where (((" & sql2export & ". GPID)=[Forms]![frmFEFindQA]![GPID]));"
Else: s = "select * from " & sql2export
End If
On Error Resume Next
CurrentDb.QueryDefs.Delete "xlsExport"
Set qdf = CurrentDb.CreateQueryDef("xlsExport", s)
Set xlApp = GetObject(, "excel.application")
If (Err.Number = 0) Then
Set xlApp = GetObject("Excel.Application")
xlApp.Visible = True
Set ws = xlApp.Sheets.Add
Set MyDatabase = CurrentDb
MyDatabase.QueryDefs.Delete ("xlsExport")
Set MyQueryDef = MyDatabase.CreateQueryDef("xlsExport", s)
Set MyRecordset = MyDatabase.OpenRecordset("xlsExport") ‘<------ empty
With xlApp
.ws.Select
.ActiveSheet.Range("a2").CopyFromRecordset MyRecordset
For i = 1 To MyRecordset.Fields.Count
xlApp.ActiveSheet.Cells(1, i).Value = MyRecordset.Fields(i - 1).Name
Next i
xlApp.Cells.EntireColumn.AutoFit
End With
Else:
Set xlApp = CreateObject("Excel.Application")
xlApp.Visible = True
DoCmd.TransferSpreadsheet acExport, acSpreadsheetTypeExcel9, "xlsExport", "C:\Users\" & Environ("USERNAME") & "\Documents\VehInfoExp", True
xlApp.Workbooks.Open "C:\Users\" & Environ("USERNAME") & "\Documents\InfoExp.xls", True, False
End If
Err.Clear
On Error GoTo 0
Set xlApp = Nothing
End Sub
Arg, I found the answer. After a week of trying I decided to post the question and then I figured it out an hour later.
The issue is in the "Where" clause of the SQL. I needed to capture the value of the form as a variable and put it into the equation. For some reason while the macro is running the referenced part of the form was valued as nothing. So nothing was returned.
Therefore, the following line of SQL:
s = "select * from " & sql2export & " Where (((" & sql2export & ".GPID)=[Forms]![frmFEFindQA]![GPID]));"
Became:
s = "select * from " & sql2export & " Where (((" & sql2export & ".GPID)=""" & strWhere & """));"
Thank you for letting me post.

How can I get the connection string in vba from the linked tables in access 2013?

I have this linked tables on my access and I want to get the connection of it
Here is the screenshot
In my vba I tried this code but does not work because my stored procedure does not execute
Dim adocmd As New ADODB.Command
DoCmd.Maximize
adocmd.ActiveConnection = Application.CurrentProject.Connection.ConnectionString
adocmd.CommandType = adCmdStoredProc
adocmd.CommandText = "spr_DECSBillingSchedule"
adocmd.CommandTimeout = 0
On Error Resume Next
adocmd.Execute , , adExecuteNoRecords
Set adocmd = Nothing
On Error GoTo 0
How can I possibly fix this issue? thanks!
The definitions for tables are stored in a system table called MSysObjects, the connection string is in field Connect. You can access this table to get the connection string as and when you want to run the sproc (you'll need to reference a table you know is in the same database, I have front ends linked to multiple databases), though as the connection string does not change you may be better to set it to a global variable or just hard code it in (which i have fallen into the habit of doing).
NOTE: This is as per MS Access 2007, it is the only one I have installed
Below is an example of a function I use to execute a sproc, the sproc returns a value to confirm it has completed successfully, which is returned in #Ret. Hope this helps.
Function LogImportFile(strFile As String) As Long
On Error GoTo Err_Handle_LogImportFile
Set cnn = CreateObject("ADODB.Connection")
cnn.ConnectionString = "DRIVER={SQL Server};SERVER=[Server];DATABASE= _
[DatabaseName];Trusted_Connection=Yes"
' The above is for linking to a SQL Server table using a DSN less connection
' which I would highly recommend (DSN less) if you plan to distribute your
' database
cnn.Open cnn.ConnectionString
Set cmd = CreateObject("ADODB.Command")
cmd.ActiveConnection = cnn
cmd.CommandType = adCmdStoredProc
cmd.CommandText = "cmsUser.usp_LogImportFile"
cmd.CommandTimeout = 0
Set param = cmd.CreateParameter("#FileName", adVarChar, adParamInput, _
200, strFile)
cmd.Parameters.Append param
Set param = cmd.CreateParameter("#Ret", adInteger, adParamOutput)
cmd.Parameters.Append param
cmd.Execute
LogImportFile = cmd.Parameters("#Ret")
Exit_Proc:
Set cnn = Nothing
Set cmd = Nothing
Set param = Nothing
Exit Function
Err_Handle_LogImportFile:
Msgbox "LogImportFile - " & Err.Number & " - " & Err.Description
LogImportFile = -1
GoTo Exit_Proc
End Function

Inconsistent Stored Procedure Calls from One PC to Another

I have an unbound Access form that populates a text box with data retrieved from SQL Server 2008 via a stored procedure GetIssueComponents(). Below is the code for this. The code works. My problem is that some PCs will consistently execute the function calls and retrieve the data all within a second. However, other computers will take tens of seconds to do this. We even have one machine that takes a full minute or two! Every machine is different on how long they take, but each one is consistent with the timing.
It doesn't seem to be anything directly related to hardware as many of the computers are identical configurations, and in fact the worst computer we have is one of the very fastest at executing the procedure! The ODBC drivers are identical on all the computers as well. All the computers are running Windows XP and I believe they all have the same patches installed. I don't know where else to look, please help!
Global adoCnn As New ADODB.Connection
Public Function ADO_ConnectionInitialize() As Boolean
Const DEBUG_THIS_PROC_NAME = "ADO_ConnectionInitialize"
Debug_Proc_Start DEBUG_THIS_PROC_NAME, True
On Error GoTo ADO_ConnectionInitialize_Error
ADO_ConnectionInitialize = False
If adoCnn.state = adStateClosed Then
adoCnn.ConnectionString = "Provider=SQLOLEDB;Data Source=10.10.10.10;Initial Catalog=" & DATABASE_NAME & ";Integrated Security=SSPI;"
adoCnn.Open
End If
ADO_ConnectionInitialize = True
ADO_ConnectionInitialize_Error:
Select Case Debug_Proc_End(DEBUG_THIS_PROC_NAME, True)
Case vbAbort
Debug.Assert False
Resume
Case vbRetry
Resume
Case vbIgnore
Resume Next
Case vbCancel
Case vbOK
Case Else
End Select
End Function
Public Function ADO_StoredProcedure(ProcName As String, Optional parameters As Variant) As ADODB.parameters
Dim comm As ADODB.Command
Dim p As Variant
Dim param As ADODB.Parameter
If ADO_ConnectionInitialize() Then
Set comm = New ADODB.Command
With comm
.ActiveConnection = adoCnn
.CommandType = adCmdStoredProc
.CommandText = ProcName
For Each p In parameters
If IsNull(p(3)) Then
Set param = .CreateParameter(p(0), p(1), p(2))
Else
Set param = .CreateParameter(p(0), p(1), p(2), p(3))
End If
.parameters.Append param
If p(2) = adParamInput Or p(2) = adParamInputOutput Then
.parameters(p(0)).value = p(4)
End If
Next
End With
comm.Execute
Set ADO_StoredProcedure = comm.parameters
Set comm = Nothing 'Memory leak if this isn't done??
End If
End Function
Public Function GetIssueComponents(ByVal issueID As Long) As String
Const DEBUG_THIS_PROC_NAME = "GetIssueComponents"
Debug_Proc_Start DEBUG_THIS_PROC_NAME
On Error GoTo GetIssueComponents_Error
Dim params As ADODB.parameters
Dim p As ADODB.Parameter
Set params = ADO_StoredProcedure("dbo.GetIssueComponents", Array( _
Array("#ReturnValue", _
ADODB.DataTypeEnum.adInteger, _
ADODB.ParameterDirectionEnum.adParamReturnValue, _
Null, _
Null), _
Array("#issueID", _
ADODB.DataTypeEnum.adInteger, _
ADODB.ParameterDirectionEnum.adParamInput, _
Null, _
issueID), _
Array("#Components", _
ADODB.DataTypeEnum.adVarChar, _
ADODB.ParameterDirectionEnum.adParamOutput, _
255, _
Null) _
))
GetIssueComponents = params("#components").value
GetIssueComponents_Error:
Select Case Debug_Proc_End(DEBUG_THIS_PROC_NAME)
Case vbAbort
Debug.Assert False
Resume
Case vbRetry
Resume
Case vbIgnore
Resume Next
Case vbCancel
Case vbOK
Case Else
End Select
End Function
I don't have an answer as to why the connection performs differently from one pc to the next, but I did find that changing form OLE DB to ODBC completely eliminates the problem. My new connection string is as follows:
adoCnn.ConnectionString = "DRIVER=sql server;SERVER=" & DATABASE_IP & ";APP=Microsoft Office 2010;DATABASE=" & DATABASE_NAME & ";Network=DBMSSOCN;Trusted_Connection=Yes"
So this counts as a work around, but I would still love to hear details about OLE DB and why it performs so inconsistently.