How do I delete rows from an access database using a script? - database

I am trying to programmatically remove rows from a Microsoft Access Database using a script (such as vbscript or whs).
It looks like there are two or more engines that can be used to connect to an mdb file which are the ADO extension Jro.JetEngine or DAO.Database DBEngine.
In addition to this, there is a column in the table called CreatedDate which contains the date that the entry was created.
I plan to use this to remove entries that are older than N days old.
How would I achieve something like this?

You need something like this script.
connectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & yourDatabase & ";"
sql = "delete from yourTable where CreateDate < " & yourDateString
set cn = createobject("ADODB.Connection")
set cmd = createobject("ADODB.Command")
cn.open connectionString
cmd.ActiveConnection = cn
cmd.CommandText = sql
cmd.execute
cn.Close
The specific connection string for your MS Access version can be had at connectionstrings.com

Related

Running SQL queries from inside spreadsheet cells

I have an Excel spreadsheet with several SQL queries stored in different cells and I'd like to execute these queries on SQL Server to generate a new sheet where each cell is the query result from the original spreadsheet. The idea behind this is to preserve the sheet formatting when generating the results (conditional formatting and etc.).
Something like this:
Input spreadsheet:
Database
Information A
Information B
DB 1
SQL Query 1
SQL Query 2
DB 2
SQL Query 3
SQL Query 4
Output spreadsheet:
Database
Information A
Information B
DB 1
Result of Query 1
Result of Query 2
DB 2
Result of Query 3
Result of Query 4
I wasn't able to find ideas on how to do exactly this during my research of the subject, but I do believe it should be doable using either VBA or some scripting language.
Any thoughts on how should I approach this?
I've got it done using Power Query. It was way easier than I thought. Special thanks to Jacek Wróbel for providing the idea in the comments.
As an aside, you could do something like this.
Sub ADOExcelSQLServer()
Dim Cn As ADODB.Connection
Dim Server_Name As String
Dim Database_Name As String
Dim User_ID As String
Dim Password As String
Dim SQLStr As String
Dim rs As ADODB.Recordset
Set rs = New ADODB.Recordset
Server_Name = "EXCEL-PC\SQLEXPRESS" ' Enter your server name here
Database_Name = "Northwnd" ' Enter your database name here
User_ID = "" ' enter your user ID here
Password = "" ' Enter your password here
SQLStr = "SELECT * FROM Orders" ' Enter your SQL here
Set Cn = New ADODB.Connection
Cn.Open "Driver={SQL Server};Server=" & Server_Name & ";Database=" & Database_Name & _
";Uid=" & User_ID & ";Pwd=" & Password & ";"
rs.Open SQLStr, Cn, adOpenStatic
With Worksheets("Sheet1").Range("A1:Z500")
.ClearContents
.CopyFromRecordset rs
End With
rs.Close
Set rs = Nothing
Cn.Close
Set Cn = Nothing
End Sub
That sits in a VBA Module. Of course, you could store the SQL in an Excel cell, and do this...
SQLStr = Worksheets("Sheet1").Range("A1").Value
Also, you could loop through a bunch of cells and run a bunch of SQL jobs.
Your own imagination is your only limitation.

Using both Excel and Microsoft SQL Server Connection Strings

My task is to add new records from an excel table to a Microsoft SQL Server table, and to do this, I was planning on using ADODB objects; however, my SQL statement is not executing, and I think it has something to do with my connection strings.
In my code, I wrote down the SQL statement that I plan on using in the end, but when I tried:
sql = "SELECT * FROM [Provider=SQLOLEDB;Data Source=hpwfh-ssql01; _
Initial Catalog=HPW DataIntegrated Security=SSPI;Trusted_Connection=Yes].Hubspot_Data"
(a simple select statement) it didn't even work.
Sub update1()
Dim cn, rs As Object, path As String, name As String, sql As String, file As String
path = "T:\Marketing\Data Analytics\Hubspot data for SQL"
name = "Hubspot_Data"
file = path & "\" & name & ".xlsx"
Set cn = CreateObject("ADODB.Connection")
With cn
.Provider = "Microsoft.ACE.OLEDB.12.0"
.connectionstring = "Data Source=" & file & ";Extended Properties=""Excel 12.0 Xml;HDR=YES;Readonly=false;IMEX=0"";"
.Open
End With
sql = "INSERT INTO [Provider=SQLOLEDB;Data Source=hpwfh-ssql01;Initial Catalog=Hubspot_Data;Integrated Security=SSPI;Trusted_Connection=Yes].Hubspot_Data " & _
"SELECT * FROM (SELECT * FROM [Provider=SQLOLEDB;Data Source=hpwfh-ssql01;Initial Catalog=Hubspot_Data;Integrated Security=SSPI;Trusted_Connection=Yes].Hubspot_Data" & _
"EXCEPT SELECT * FROM [hubspot-crm-exports-sql-data-20$])"
Set rs = cn.Execute(sql)
End Sub
Just a side note: the table is named the same thing as the database
For this code, I have gotten three different errors:
The Microsoft Access database engine could not fin the object 'Area' Make
sure the object exists and that you spell its name and the path name
correctly. (And I did not misspell Hubspot_Data)
External table is not in the expected format.
The Microsoft Acess database engine cannot open or write to the file
(My File Path)'\My Documents\Provider=SQLOLEDB.XLSX'. It is already opened
exclusively by another use, or you need permission to view and write its
data.
Clearly the computer is going to the wrong place to retrieve the table it needs, and I have no idea where I went wrong. Thanks for the help.
First of all you need 2 connections - one for SQLSvr and one for Excel.
Then query your source (Excel) and do a separate insert into SQLSvr. You are not going to be able to mix these into one query.
Sub SelectInsert()
Dim cn As Object, rs As Object, sql As String
Dim conSQL As Object, sInsertSQL As String
'---Connecting to the Data Source---
Set cn = CreateObject("ADODB.Connection")
With cn
.Provider = "Microsoft.ACE.OLEDB.12.0"
.ConnectionString = "Data Source=" & ThisWorkbook.Path & "\" & ThisWorkbook.Name & ";" & "Extended Properties=""Excel 12.0 Xml;HDR=YES"";"
.Open
End With
Set conSQL = CreateObject("ADODB.Connection")
With cn
.Provider = "SQLOLEDB"
.ConnectionString = "Server=myServerAddress;Database=myDataBase;Trusted_Connection=True;"
.Open
End With
'---Run the SQL SELECT Query---
sql = "SELECT * FROM [Sheet1$]"
Set rs = cn.Execute(sql)
Do 'the insert. Each rs(n) represents an Excel column.
sInsertSQL = "INSERT INTO table VALUES(" & rs(0) & ";" & rs(1) & ";" & rs(2) & ")"
conSQL.Execute sInsertSQL
rs.MoveNext
Loop Until rs.EOF
'---Clean up---
rs.Close
cn.Close
conSQL.Close
Set cn = Nothing
Set conSQL = Nothing
Set rs = Nothing
End Sub
get properties of your database from "SQL Server Object explorer" and copy the exact same connection string. then copy it to the "appsettings.json" file of your project. It looks like this :
"connectionStrings": {
"ApiDbConnectionString": "Server=(localdb)\\mssqllocaldb;Database=ApiDB;Trusted_Connection=True;"
}
then you need to create an object in your connection string and open a connection to the database using that object, then write your SQL query to the database

Unable to open Linked Access 2003 table to MS SQL Server in VBA code

I have a table in Access 2003 that is linked to a MS SQL server table.
I am able to go into the Access table, manually update it and see the changes
reflected in the MS Sql server table.
However, I'm unable to even just open the table and put the result in the record set in my VBA code.
Set rs = CurrentDb.OpenRecordset("dbo_tbl_EventLogs", dbOpenTable)
(rs is always at nothing)
The same line of code works on a 'local' Access table.
Consider using dbOpenDynaset option which is used by default for linked tables or stored queries whereas dbOpenTable is used for local tables as mentioned for OpenRecordset() method:
If you open a Recordset in a Microsoft Access workspace and you don't
specify a type, OpenRecordset creates a table-type Recordset, if
possible. If you specify a linked table or query, OpenRecordset
creates a dynaset-type Recordset.
Set rs = CurrentDb.OpenRecordset("dbo_tbl_EventLogs", dbOpenDynaset)
You need to connect to your DB using ADO. Is simple and easy. Just change to your info and enjoy it.
Dim cn As ADODB.Connection
Dim rs As ADODB.Recordset
ServerName = "yourServer,yourPort(example: 1442)" 'Enter your server name and a port here
DatabaseName = "yourDBinTheServer" 'Enter your database name here
UserID = "yourUserID" 'Enter your user ID here
Password = "yourPassword" 'Enter your password here
Set rs = New ADODB.Recordset
Set cn = New ADODB.Connection
cn.Open "Driver={SQL Server};Server=" & ServerName & ";Database=" & DatabaseName & ";Uid=" & UserID & ";Pwd=" & Password & ";"
rs.open yourQueryAsString, cn
Make sure you store the user credentials used to connect to the database...
(attribute dbAttachSavePWD)

Calling Stored Procedure from MSAccess fails, but running the exact same command from Sql Server Manager works

I have an Access DB that has a bunch of linked tables from a SQL Server database. The Access DB calls a stored procedure on the SQL Server database that updates data on a form.
Dim sql As String
Dim cnn As ADODB.Connection
Set cnn = New ADODB.Connection
cnn.ConnectionString = "DSN=Records"
cnn.CommandTimeout = 90
cnn.Open
sql = "exec myStoredProcedure #param1=" & Me.txtParam1Field & ", #param2=" & Me.txtParam2Field
cnn.Execute sql
Set cnn = Nothing
frmMyForm.Requery
When I run this it either times out, if the CommandTimeout value isn't long enough, or it executes, but doesn't actually execute myStoredProcedure for some reason. If I take the string sql and past it into Sql Server Manager, myStoredProcedure executes in less than a second and everything works great.
I've tried debugging over this code in Access, but I'm not getting any useful results when I step over cnn.Execute sql.
Depending on the values of txtParam1Field and txtParam2Field you probably want to enclose the values with single quote like so:
sql = "exec myStoredProcedure #param1='" & Me.txtParam1Field & "', #param2='" & Me.txtParam2Field & "'"
If we take your original code and assume that txtParam1Field is equal to 1 and txtParam2Field is equal to John then your generated sql will not execute because it will look like this:
exec myStoredProcedure #param1=1, #param2=John
Your best bet is to output the value of "sql" variable in debug window and run that exact statement in sql query manager. That will tell you exactly where the problem is if it's malformed SQL.
You could try setting the Prepared property to false on the command object. This causes a recompile of the procedure before execution, but could result in a better plan depending on the parameters that are sent.
Dim sql As String
Dim cnn As ADODB.Connection
Dim Cmd As ADODB.Command
Set cnn = New ADODB.Connection
cnn.ConnectionString = "DSN=Records"
cnn.CommandTimeout = 90
cnn.Open
sql = "exec myStoredProcedure #param1=" & Me.txtParam1Field & ", #param2=" & Me.txtParam2Field
Set Cmd = New ADODB.Command
Set Cmd.ActiveConnection = cnn
Cmd.CommandType = adCmdText
Cmd.CommandText = sql
Cmd.Prepared = False
Cmd.CommandTimeout = 300
Cmd.Execute

How to execute an update statement from Excel macro to SQL Server

I have an Excel 2007 file in which I do a lot of dataprocessing (merely reporting) using remote connections to a SQL Server db. When a report has been processed I would like to update a specific field of a table that resides on the same SQL Server db. Something like:
UPDATE [MetricsCollection].[dbo].[tblBatchFeeder]
SET datReportProcessed = CURRENT_TIMESTAMP
WHERE intID = 48
What's the simplest way to approach this?
Kind regards,
Paul.
It would probably be best to have a procedure on the server.
Dim cn As New ADODB.Connection
Dim cmd As New ADODB.Command
cn.Open ServerConnect ''http://connectionstrings.com
cmd.ActiveConnection = cn
cmd.CommandText = "UpdateMetrics" ''stored procedure
cmd.CommandType = adCmdStoredProc
cmd.Parameters("#intID").Value = 48 ''Parameter
cmd.Execute recs

Resources