INSERT statement status in VBA using ADODB - sql

Say i have a table in Excel:
TableA:
ID,
Name,
Work,
DOB
I have an insert query like:
Insert into TableA(ID,Name,Work,DOB) values (....);
I have created the code to upload this data into SQL Server database using ADODB
The upload works fine but i am trying to have it fill the status of the upload such (Pending, Successful) next to each row. Is there any way to do it?
The ending part of my code is:
For lp = 0 To qryindex - 1 'this loop is used to get query from the array which is stored in previous loop
con.Open 'open the connection
con.Execute qryary(lp), dbfailonerror ' execute the query one by one according to index value
oldValue = Application.ActiveCell.Value
con.Close
Next lp
MsgBox "Data Updated Successfully"
ThisWorkbook.RefreshAll
I need it to update the coulmn(F) as each query in the array is successfully posted

Related

MS Access Database insert values on a column using vba and sql query

Is there any way to add a column into an MS Access database using VBA and SQL query and then insert values using formulas from other column.
As an example, I want to create a column employee and it should have calculated values on all the records. I want to use LEFT(col2, 3) in the employee field.
This is my code:
Sub createcolumn()
Dim objAccess As Object
Set objAccess = CreateObject("Access.Application")
Call objAccess.OpenCurrentDatabase("H:\VBA\Array Practice\Database1array.accdb")
objAccess.CurrentProject.Connection.Execute ("ALTER TABLE Company ADD COLUMN employee CHAR ")
End Sub
Sub insertvalues()
Dim objAccess As Object
Set objAccess = CreateObject("Access.Application")
Call objAccess.OpenCurrentDatabase("H:\VBA\Array Practice\Database1array.accdb")
objAccess.CurrentProject.Connection.Execute "INSERT INTO Employee (Gross) VALUES LEFT([full_name], 3)"
End Sub
I am able to create a new column but could't insert the value.
You can directly update the table using column FULL_NAME instead of inserting. I have tested the following code and it is working.
Sub test()
Dim dbs As Database
Set dbs = OpenDatabase("Database1.accdb")
dbs.Execute "UPDATE EMPLOYEE SET GROSS=LEFT(FULL_NAME, 3)"
dbs.Close
End Sub
You added a column to a table named Company, but you are attempting to insert values to a table named employee.
If the table named company as records then an update statement is what you need to add values into the new column employee, but if the table does not have any record, then an insert statement can be used to add values into the employee field.

Insert X rows into child table based on parent field

Trying to insert a set number of rows into a child table based on a number entered into a parent table
parent (licenseID, poolSize)
child (nodeID, licenseID)
I was looking into using an After Insert trigger on the parent table but could not figure out how to loop a create record command.
Is this possible to do with macros or should I be looking at VBA code? (MS ACCESS 2010)
First of all, I would never enter anything directly into a table. Giving your users that kind of ability is always going to end up in some form of misery and regret.
I would creat a form to take the number, and then use code behind a "Submit" button to loop the required number of times. Something like (this code is entirely untested):
Dim db as Database
Dim rec as Recordset
Dim X as Double
Set db = CurrentDB
Set rec = db.OpenRecordset ("Child")
Do for X = 1 to Me.txtNumberOfEntries
rec.AddNew
rec("LicenseID") = me.txtLicenseID
rec.Update
Next X
'Always clear out your variables
Set rec = Nothing
Set db = Nothing

How to increment ID by 1 in SQL Server (backend) when INSERT code is written in vba (frontend)?

I am new to this forum.
I have the following environment: an Access frontend client that is connected to a database on SQL Server (backend). I would like to use an Access form to enter data that is associated with a specific ID number (in database Table). Ideally the ID will automatically increment when an INSERT is made to the Table. The vba code (based on the SQL query) I wrote is the following:
Option Compare Database
Option Explicit
Private Sub List0_Click()
Dim HelloWORLD As String
Dim dbsCurrent As Database
Set dbsCurrent = CurrentDb
CurrentDb.Execute "INSERT INTO Table1 (TESTING_1, TESTING_2) VALUES (" & 9 & "," & HelloWORLD & ")"
End Sub
The code is compiling but it is not appending the Table1 like it is supposed to do. Please Help.
You can use sequences.
You can creates sequence MySequence1 and use it:
CurrentDb.Execute "INSERT INTO Table1 (TESTING_1, TESTING_2) VALUES (NEXT VALUE FOR MyDemoSequence," & HelloWORLD & ")"
Can you make the ID field an IDENTITY field within SQL Server? This will automatically increment whenever a new row is inserted. Example from Microsoft documentation:
CREATE TABLE new_employees
(
id_num int IDENTITY(1,1),
fname varchar (20),
minit char(1),
lname varchar(30)
)
The first number is the seed, and the second is the increment, so IDENTITY(1,1) means start at '1', and increase by '1' each time.
You can retrieve the ID that was created using SELECT SCOPE_IDENTITY(); following the insert if necessary.

MS SQL get values after INSERT

I am facing an issue where I need to calculate some data based on existing data, then insert that data and finally, return it to an Excel file using VBA.
I have successfully been able to create a stored procedure that returns a table of values after inserting:
[...]
INSERT INTO [ExcelRGA] (RM_prefix, RM_suffix, editing, createdBy, editedBy) values (#RM_prefix, #RM_suffix, 1, #user, #user);
DECLARE #tab table (RM varchar(20))
INSERT #tab SELECT (#RM_prefix +'-' + right('00' + #RM_suffix, 3)) as 'RM';
SELECT * FROM #tab
END
and this works! However, I am unable to get the values it is returning using VBA
Set oRS = New ADODB.Recordset
Set cmd = New ADODB.Command
Dim objRec As Object
cmd.ActiveConnection = oCon
cmd.CommandType = adCmdStoredProc
cmd.CommandText = "dbo.newRM"
cmd.Parameters.Refresh
cmd.Parameters("#user").Value = "john"
Set oRS = cmd.Execute()
but I try to do something like
while not oRS.eof
....
wend
get an error message stating that the recordset is closed and I cannot do my thing.
All I am trying to do is secure the information that I have computed (RM_prefix and RM_suffix), insert them into my table and return them to my Excel file.
If there is a way to do this without using a store procedure (such as a function) that would also be great!
Please keep in mind that this is a multi-user environment, so generating the values in Excel, sending them to the SQL server for an insert doesn't give a 100% guarantee regarding the uniqueness of said data.
Thank you all for your precious help and inputs!
Peter
You need something like this -
Private Function GetIDENTITY() As Long
oRS.Open "SELECT ##identity AS NewID", oCon
If Not IsNull(oRS.Fields("NewID")) Then
GetIDENTITY = oRS.Fields("NewID"): oRS.Close
Else
MsgBox "Error: Identity value not returned.", vbCritical
End
End If
End Function
Actually, the issue was coming from the SQL Stored Procedure. I've added
SET NOCOUNT ON;
right before the
INSERT INTO [ExcelRGA] (RM_prefix, RM_suffix, editing, createdBy, editedBy) values (#RM_prefix, #RM_suffix, 1, #user, #user);
And it has solved my problem! I can now browse the recordset in VBA.
Thank you all for your help and inputs!

Insert INTO in vb.net

I have 2 databases. In first one I have 10 tables. Second one is only 1 table. I would like to select 1 columns from each table from 1st database and Insert INTO another database. How can I manage this using INSERT INTO statement in VB.net?
I deleted my previous answer saying that you have to manually copy over the data. For now, let's assume you want to do this with a SELECT INTO statement.
The following code shows you how to execute a SQL command on your database using a ADO.NET connection and command object:
' Open a connection to your database (e.g. in a SQL Server): '
Using connection As IDbConnection = New SqlConnection("<Connection string>")
connection.Open()
Try
' Define the SQL command to be executed here: '
Dim command As IDbCommand = connection.CreateCommand()
command.CommandText = "SELECT <...> INTO <...>"
' Execute the command: '
command.ExecuteNonQuery()
Finally
connection.Close()
End Try
End Using
I hope this helps:
From sql side, you'll just need to write a stored procedure to insert into (ten) hash tables and select/insert them into your target table.
In Vb.net, you'll need: a connection object and a command object to call your stored procedure