I'm fairly new to this. I'm trying to write a procedure in VBA that executes a stored procedure from excel and returns the record set. It currently returns the results of the stored procedure in spreadsheet 2 but I've had to hard code the parameter into the SQL code. Here is what I have pinched from other online forums.
Option Explicit
Public Sub OpenConnection()
'Set the variables
Dim conn As ADODB.Connection
Dim str As String
Dim cmd As ADODB.Command
Dim rs As ADODB.Recordset
Dim fld
Dim i As Integer
'Error handler
On Error GoTo errlbl
'Open database connection
Set conn = New ADODB.Connection
'First, construct the connection string.
'ODBC CONNECTION YOU'VE ALREADY SET UP:
conn.ConnectionString = "DSN=PC_Tool_Coding"
conn.Open 'Here's where the connection is opened.
Debug.Print conn.ConnectionString 'This can be very handy to help debug!
'Recordset
Set rs = New ADODB.Recordset
str = "exec Select_account_info"
'recordset is opened here
rs.Open str, conn, adOpenStatic, adLockReadOnly
If Not IsEmptyRecordset(rs) Then
rs.MoveFirst
'Populate the first row of the sheet with recordset’s field names
i = 0
For Each fld In rs.Fields
Sheet2.Cells(1, i + 1).Value = rs.Fields.Item(i).Name
i = i + 1
Next fld
'Populate the sheet with the data from the recordset
Sheet2.Range("A2").CopyFromRecordset rs
Else
MsgBox "Unable to open recordset, or unable to connect to database.", _
vbCritical, "Can't get requested records"
End If
'Cleanup
rs.Close
Set rs = Nothing
conn.Close
Set conn = Nothing
exitlbl:
Debug.Print "Error: " & Err.Number
If Err.Number = 0 Then
MsgBox "Done", vbOKOnly, "All Done."
End If
Exit Sub
errlbl:
MsgBox "Error #: " & Err.Number & ", Description: " & Err.Description, vbCritical, "Error in OpenConnection()"
Exit Sub
'Resume exitlbl
End Sub
I've looked around on how to get it to work with parameters and I just can't seem to get there. The parameter I'll be using is called #accgrpnum in SQL. Its a 12 letter string.
Many thanks to any help in advance.
Take a look at bonCodigo's link or
I've also been able to do this (with SQL Server 2008) by sending more than one statement, but separated in a SQL statement like
str = "SET #accgrpnum = 'my_account'; exec Select_account_info;"
Related
I have a simple Oracle procedure as below. I am trying to call the procedure using VB6 and extract the output from the procedure.
CREATE OR REPLACE PROCEDURE EXTRACTTXN (reportdate IN DATE, p_recordset OUT SYS_REFCURSOR) AS
BEGIN
OPEN p_recordset FOR
SELECT
TXN_ID,
TXN_ACTION,
TXN_STATUS,
TXN_DATE,
TXN_AMOUNT
FROM TRANSACTIONS
WHERE
TRUNC(TXN_DATE) = TRUNC(reportdate)
END EXTRACTTXN;
The VB Code goes like this;
Sub FetchTransactions(ByVal ReportDate As Date, cnnMine as ADODB.Connection)
On Error GoTo TrapErr
Dim cmdMine As ADODB.Command, rsMine As ADODB.Recordset
cmdMine.ActiveConnection = cnnMine
cmdMine.CommandTimeout = 300
cmdMine.CommandType = adCmdStoredProc
cmdMine.CommandText = "EXTRACTTXN"
cmdMine.Parameters.Append cmdMine.CreateParameter("reportdate", adDate, adParamInput, , Format(ReportDate, "DD-MMM-YYYY"))
cmdMine.Parameters.Append cmdMine.CreateParameter("p_recordset", adVariant, adParamOutput)
Set rsMine = cmdMine.Execute
Do While rsMine.EOF
Debug.Print rsMine!TXN_ID, rsMine!TXN_ACTION, rsMine!TXN_STATUS, rsMine!TXN_DATE, rsMine!TXN_AMOUNT
rsMine.MoveNext
Loop
rsMine.Close
Exit Sub
TrapErr:
MsgBox Err.Number & " - " & Err.Description, vbExclamation, App.ProductName
End Sub
While running the code, I get the following Error:
ORA-06550: line 1, column 7:
PLS-00306: wrong number or types of arguments in call to 'EXTRACTTXN'
ORA-06550: line 1, column 7:
PL/SQL: Statement ignored
Anything wrong in my code? Appreciate help.
Niz
The problem is that the types of your arguments as specified in your VB code don't match the types of the arguments as specified in your PL/SQL code. The most likely reason for your problem is that the Format function in VB6 returns a Variant type, not a Date type, and that Variant type is set to be a String type. See this for more information on the Format function.
In case you don't know, the way that Variant variables are set up is that they reserve 8 bytes to tell the world what the actual variable type is. So, if you pass your ReportDate in after applying the Format function to it, it will be a Variant that's telling the world it's a string. It's possible that the ADO Parameter object is happy with that (SQL Server is happy to parse properly-formatted strings into Date fields, after all) and Oracle isn't. In my limited experience with Oracle, I've found that it's fussier about that sort of thing than SQL Server.
Try losing the Format function and see if you at least get a different error.
I have managed to get this sorted. It's mainly due to me being new to Oracle and its complexity.
Here are the changes I made;
Stored Procedure Changes. Note that I have changed TRUNC(reportdate, 'DD') on the Where clause.
CREATE OR REPLACE PROCEDURE EXTRACTTXN (reportdate IN DATE, p_recordset OUT SYS_REFCURSOR) AS
BEGIN
OPEN p_recordset FOR
SELECT
TXN_ID,
TXN_ACTION,
TXN_STATUS,
TXN_DATE,
TXN_AMOUNT
FROM TRANSACTIONS
WHERE
TRUNC(TXN_DATE) = TRUNC(reportdate, 'DD')
END EXTRACTTXN;
VB Code Changes (Note that I have change the CommandText within parenthesis with a Call, removed the parameter name, changed the date format to DD/MMM/YYYY and removed the output parameter)
Sub FetchTransactions(ByVal ReportDate As Date, cnnMine as ADODB.Connection)
On Error GoTo TrapErr
Dim cmdMine As ADODB.Command, rsMine As ADODB.Recordset
cmdMine.ActiveConnection = cnnMine
cmdMine.CommandTimeout = 300
cmdMine.CommandType = adCmdStoredProc
cmdMine.CommandText = "{ call EXTRACTTXN}"
cmdMine.Parameters.Append cmdMine.CreateParameter(, adDate, adParamInput, , Format(ReportDate, "DD/MMM/YYYY"))
Set rsMine = cmdMine.Execute
Do While rsMine.EOF
Debug.Print rsMine!TXN_ID, rsMine!TXN_ACTION, rsMine!TXN_STATUS, rsMine!TXN_DATE, rsMine!TXN_AMOUNT
rsMine.MoveNext
Loop
rsMine.Close
Exit Sub
TrapErr:
MsgBox Err.Number & " - " & Err.Description, vbExclamation, App.ProductName
End Sub
The above worked perfectly.
Regards, Niz
Private Sub OK_Click(sender As System.Object, e As System.EventArgs) Handles OK.Click
If TextBox1.Text = "1234" Then
' This is the connection. You have to have this exact string, except "E:\Documents\notekeeper.mdb" will be the path to your thing instead
Dim conn As New OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=N:\Visual Studio 2010\Projects\Maths System Aid\Maths System Aid\Database7.mdb;User=;Password=;")
Try
conn.Open()
Catch ex As Exception
MsgBox("Cannot open database")
End Try
' The SQL statement / command
Dim cmd = New OleDbCommand("Insert INTO Student ([First Name], [Surname], [Username], [Password]) VALUES "("" & TextBox5.Text & "," & TextBox4.Text & "," & TextBox3.Text & "," & TextBox2.Text & "" & ")"), conn)
cmd.ExecuteNonQuery() ' Use ExecuteReader() to execute SELECT statements, but ExecuteNonQuery() for others
' Basically, the reader is like an array of all of the records that have been returned by the database
Me.Close()
StudentLogin.Show()
Else
MsgBox("Enter The Correct Confirmation code")
End If
End Sub
my problem is that it will not find my database file. I have followed the path and it is correct. Any ideas of what is the problem?
I haven't done this in quite some time but at the top of your form you should be running some imports firstly
imports system.data
Then you should define rather like this:
dim conn as new oledb.oledbconnection
Another issue I noticed in your code is that you're using the Jet provider which if memory serves correctly only works with the new databases using the .accdb extension. Try to change it to an accdb in access.. I'll go over it quick and see what I can conjure up. Hopefully that helps at least. The alternative provider if you run into issues :
("Provider=Microsoft.ACE.OLEDB.12.0.......
Is this path a local disk or a network disk? is it on another computer or a mapped network drive?
The way I connect is
Dim con As New OleDb.OleDbConnection
Dim dbProvider As String
Dim dbSource As String
dbProvider = "PROVIDER=Microsoft.Jet.OLEDB.4.0;"
dbSource = "Data Source = C:\data\database.mdb;Jet OLEDB:Database Password=******;"
con.ConnectionString = dbProvider & dbSource
con.open()
con.close()
This should work perfect but use your path and password if you have one
I'm new to Visual Basic 6 and I'm trying to execute an stored procedure and get the result into a text field variable.
The code below shows this error: error 91
"Object variable or With block variable not set" runtime error
Dim auxInfo As rdoResultset
Dim Cone As ADODB.Connection
SQL = "EXEC [mybase].[dbo].[myStoredProcedure] '" & var1 & "', '" & var2 & "','" & var3 & "'"
Set auxInfo = Cone.Execute(SQL)
myTextField.Text = Trim(auxInfo("fistColumn"))
auxInfo.Close
And if I change the following:
Set auxInfo = Cone.Execute(SQL)
into
Set auxInfo = UAN.OpenResultset(SQL, rdOpenDynamic, rdConcurValues, 0)
'with UAN I call the funcion that connects to my database. The connection works, I've tested it.
I get a new error: error 13 type mismatch
Could please tell what am I doing wrong?
Thanks!!
As the error says, You've not actually set Cone to anything.
You're missing the Set Cone = New ADODB.Connection.
I am quite new in vbs and I would like some of your help on this script.
Basically I need a script that will get my current computername, look into a csv file to get the new related computername and then use that new name to move the corresponding account in the AD to a new OU.
I already know how to get my current computername and how to move an object to a new OU, these are things I have already done, but I am really not confident about parsing the csv looking for the new computername based on my current one.
The new name is the value just after the current name in the csv file. Only separted by a coma.
Edit 1
I tried your solution but as stated in the comments I think there are some things that I don't get. I might misuse the recordset or do not know how to retrieve the information from it. Here is my full script so you can see what I am doing:
'Get the old/current computername
Set wshShell = WScript.CreateObject( "WScript.Shell" )
OldComputerName = wshShell.ExpandEnvironmentStrings( "%COMPUTERNAME%" )
'Parse the xml file to get the related new computername
Dim CONNECTION : Set CONNECTION = CreateObject("ADODB.CONNECTION")
Dim RECORDSET : Set RECORDSET = CreateObject("ADODB.RECORDSET")
CONNECTION.Open "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\test\;Extended Properties=""text;HDR=YES;FMT=Delimited"""
RECORDSET.Open "SELECT NewComputerName FROM ComputerList.csv WHERE ComputerName = '& OldComputerName'", CONNECTION, 3, 3
'Move the new computername in the target AD to a new OU
Dim NewComputerName
Dim OldLocation
NewComputerName = RECORDSET
OldLocation = "LDAP://CN=" & NewComputerName & ",OU=Staging,OU=Workstations,DC=contoso,DC=lab"
Set objNewOU = GetObject("LDAP://OU=Migration,OU=Workstations,DC=contoso,DC=lab")
Set objMoveComputer = objNewOU.MoveHere(OldLocation, vbNullString)
' It does not work as it said Error: Wrong number of arguments or invalid property assignment pour la ligne:
' OldLocation = "LDAP://CN=" & NewComputerName & ",OU=Staging,OU=Workstations,DC=contoso,DC=lab"
Thanks a lot for your help ! :)
You can use ADO to read CSV (and other delimited) files. The gory details are discussed in this article. Sample code for reading a simple CSV file using VBScript is as follows:
Note: the CSV file needs a header line in order for ADO to use column names:
ComputerName,NewComputerName
Computer #1,Other Computer #1
Computer #2,Other Computer #2
Computer #3,Other Computer #3
VBScript Code:
option explicit
dim CONNECTION : set CONNECTION = CreateObject("ADODB.CONNECTION")
dim RECORDSET : set RECORDSET = CreateObject("ADODB.RECORDSET")
CONNECTION.Open "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\Folder\Containing\CSV\File\;Extended Properties=""text;HDR=YES;FMT=Delimited"""
RECORDSET.Open "SELECT * FROM data.csv WHERE ComputerName = '" & OldComputerName & "'", CONNECTION, 3, 3
' //// For testing \\\\
WScript.Echo RECORDSET.Source
' \\\\ For testing ////
if RECORDSET.EOF then
WScript.Echo "Record not found"
WScript.Quit
else
dim NewComputerName : NewComputerName = RECORDSET("NewComputerName") & ""
WScript.Echo NewComputerName
end if
Note that this code might not work on 64-bit OS -- not directly. You must run 32-bit version of CScript/WScript like so:
%windir%\SysWoW64\cscript c:\Path\To\test.vbs
Ok the script works perfectly now thanks to your modifications ! :)
But I've got one more trouble, it seems that I cannot open the csv file in the FROM clause when this file have - in the name.
Like : CONTOSO-US-ComputerList.csv I get the error Syntax error in FROM clause
But when I use a file name without dashes there is no problem.
I know it is a detail but I have no choice than having a file with dashes in the name :/
Thanks again for your help :) Very much appreciated !!
EDIT:
Nevermind I found the solution thanks to the scriptingguys !
The request now looks like this:
strFile = "[CONTOSO-ComputerList.csv]"
RECORDSET.Open "SELECT * FROM " & strFile & " WHERE ComputerName = '" & OldComputerName & "'", CONNECTION, 3, 3
I wrote a store procedure.
CREATE PROCEDURE [dbo].[Test]
(#Num int)
AS
BEGIN
IF #Num = 1
PRINT 'This is One';
ELSE
PRINT 'This is Another';
END
I implement in .net
Dim SqlCmd as new sqlcommand
DIm SqlCon as new sqlconnection
sqlcon.connectionstring =""
sqlCmd.connection =con
sqlcon.open()
sqlcmd.commandtext ="Test"
Sqlcmd.commandtype = commandtype.storeprocedure
I don't know how to get print message from store procedure
Please, help me.
You need to use a SELECT statement or a RETURN
PRINT is used to print messages on console for debugging purposes, you cannot get it as an SP result, rather you should use OUTPUT variable for this.