With reference to this question I run the below query to
a) get the campaigns in Column A and
b) include the alias in the SQL as header for the Column A.
Sub ConnectDB5()
Dim conn As New ADODB.Connection
Dim rs As New ADODB.Recordset
Dim dateVar As Date
Set conn = New ADODB.Connection
conn.ConnectionString = "DRIVER={MySQL ODBC 5.1 Driver}; SERVER=localhost; DATABASE=bi; UID=username; PWD=password; OPTION=3"
conn.Open
strSQL = " SELECT 'campaign' UNION ALL SELECT " & _
" cID AS Campaign " & _
" FROM PDW_DIM_Offers_Logistics_history " & _
" WHERE DATE(insert_timestamp) = ""2020-02-24"" "
Set rs = New ADODB.Recordset
rs.Open strSQL, conn, adOpenStatic
Sheet4.Range("A1").CopyFromRecordset rs
rs.Close
conn.Close
End Sub
This query works perfectly.
Now, I added one additional column in the SQL query:
Sub ConnectDB5()
Dim conn As New ADODB.Connection
Dim rs As New ADODB.Recordset
Dim dateVar As Date
Set conn = New ADODB.Connection
conn.ConnectionString = "DRIVER={MySQL ODBC 5.1 Driver}; SERVER=localhost; DATABASE=bi; UID=username; PWD=password; OPTION=3"
conn.Open
strSQL = " SELECT 'campaign' UNION ALL SELECT " & _
" cID AS Campaign, " & _
" SUM(order_quantity) AS Quantity" & _
" FROM PDW_DIM_Offers_Logistics_history " & _
" WHERE DATE(insert_timestamp) = ""2020-02-24"" " & _
" GROUP BY 1"
Set rs = New ADODB.Recordset
rs.Open strSQL, conn, adOpenStatic
Sheet4.Range("A1").CopyFromRecordset rs
rs.Close
conn.Close
End Sub
With this I get:
runtime error '-2147217887 (80040e21)'
What do I need to change in my VBA to
a) get the campaigns in Column A and the Quantity in Column B
b) include the alias in the SQL as header for the Column A and Column B?
I think you need to fix the heading row:
strSQL = " SELECT 'campaign', 'Quantity' UNION ALL SELECT " & _
UNION requires all dataset to have the same number of columns.
When you use union you must have the same number of columns in your selects.
Try this:
strSQL = " SELECT 'campaign', '' AS Quantity UNION ALL SELECT " & _
" cID AS Campaign, " & _
" SUM(order_quantity) AS Quantity" & _
" FROM PDW_DIM_Offers_Logistics_history " & _
" WHERE DATE(insert_timestamp) = ""2020-02-24"" " & _
" GROUP BY 1"
In your first select the Quantity column will have nothing like result.
Related
Sub Get_Data()
Dim conn As New ADODB.Connection
Dim rs As New ADODB.Recordset
Dim dateVar As Date
Set conn = New ADODB.Connection
conn.ConnectionString = "DRIVER={MySQL ODBC 5.1 Driver}; SERVER=localhost; DATABASE=bi; UID=username; PWD=password; OPTION=3"
conn.Open
strSQL = " SELECT " & _
" Products " & _
" FROM Logistics " & _
" WHERE DATE(insert_timestamp) = ""2020-02-24"" " & _
" GROUP BY 1"
Set rs = New ADODB.Recordset
rs.Open strSQL, conn, adOpenStatic
Sheet5.Range("A1").CopyFromRecordset rs
rs.Close
conn.Close
End Sub
I run the above VBA to extract values fom the database.
It works exactly how I need it.
Now, instead of having a pre-defined date within strSQL I want to use the data that is entered into Cell B1 in my Excel spreadsheet. Therefore, I changed the strSQL part in the VBA to:
strSQL = " SELECT " & _
" Products " & _
" FROM Logistics " & _
" WHERE DATE(insert_timestamp) = " & Sheet1.Range("B1") & " " & _
" GROUP BY 1"
However, now I get runtime error -2147217887 (80040e21) on rs.Open strSQL, conn, adOpenStatic.
What do I need to change in my VBA to make it work?
Consider the industry best practice of SQL parameterization using the ADO Command object which can properly handle data types without string concatenation or various formatting:
Dim conn As ADODB.Connection ' REMOVE New INITIALIZATION IN Dim LINES
Dim rs As ADODB.Recordset
Dim cmd As ADODB.Command
Dim dateVar As Date
Set conn = New ADODB.Connection
conn.ConnectionString = "DRIVER={MySQL ODBC 5.1 Driver}; ..."
conn.Open
' STRING STATEMENT WITH QMARK PLACEHOLDER
strSQL = " SELECT " & _
" Products " & _
" FROM Logistics " & _
" WHERE DATE(insert_timestamp) = ?" & _
" GROUP BY Products"
' CONVERT CELL TO DATE TYPE (IF CELL FORMATTED AS STRING)
dateVar = CDate(Sheet1.Range("B1").Value)
Set cmd = New ADODB.Command
With cmd
.ActiveConnection = conn
.CommandText = strSQL
.CommandType = adCmdText
' BIND PARAMS TO QMARK POSITIONAL PLACEHOLDER
.Parameters.Append .CreateParameter("mydate", adDate, adParamInput, , dateVar)
' PASS RESULT TO RECORDSET
Set rs = .Execute
End With
Sheet5.Range("A1").CopyFromRecordset rs
Try:
strSQL = " SELECT " & _
" Products " & _
" FROM Logistics " & _
" WHERE DATE(insert_timestamp) = '" & Format(Sheet1.Range("B1").Value, "YYYY-MM-DD") & "' " & _
" GROUP BY 1"
Just be aware, if insert_timestamp does indeed contain a time other than midnight, you might not get the results you're after without converting to just a date or altering your SQL.
I would like to take inputs from a table in Excel to perform SQL query and output it to a location in the Excel sheet.
Macro:
Sub SQL(Dim strSQL as String)
Dim cn As ADODB.Connection
Dim rs As ADODB.Recordset
strFile = ThisWorkbook.FullName
strCon = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & strFile _
& ";Extended Properties=""Excel 12.0;HDR=Yes;IMEX=1"";"
Set cn = CreateObject("ADODB.Connection")
Set rs = CreateObject("ADODB.Recordset")
cn.Open strCon
rs.Open strSQL, cn
Debug.Print rs.GetString
End Sub
SQL Query:
SELECT
e.`isin`,
b.*
FROM
`risk_reference`.`basket_debt` AS b
JOIN `risk_reference`.`etp` AS e
ON IF(
e.`parentid_override` > 0,
e.`parentid_override`,
e.`parentid`
) = b.`parentid`
AND e.`isin` = ?
AND e.`date_out` IS NULL
WHERE b.`processing_date` IN
(SELECT
MAX(processing_date)
FROM
`risk_reference`.`basket_debt`)
GROUP BY e.`isin`, b.`pk_id`
The ? in the SQL query is where I need a list of items to go in based on a table in Excel.
Should i do SQL query item by item or can i do it in one shot? If so, how do i do it? If I do line by line, how do I get to output one location in the excel?
Need some advise.
Assuming your variant of sql supports it, use IN and loop through cells to buiold the list
strsql = "SELECT e.`isin`, b.* FROM `risk_reference`.`basket_debt` AS b JOIN "
strsql = strsql & "`risk_reference`.`etp` AS e ON IF( e.`parentid_override` > 0, "
strsql = strsql & "e.`parentid_override`, e.`parentid`) = b.`parentid`"
strsql = strsql & "AND e.`isin` IN ("
dim c as range
for each c in range("your range here")
strsql = strsql & "'" & c.text & "',"
next c
strsql = strsql & ") "
strsql = strsql & "AND e.`date_out` IS NULL WHERE b.`processing_date` IN "
strsql = strsql & "(SELECT MAX(processing_date) FROM `risk_reference`.`basket_debt`) "
strsql = strsql & "GROUP BY e.`isin`, b.`pk_id`"
I am having and issue using update batch. I have a loop that goes through a recordset updating values. I have a minimum of 333 things in the batch. When it gets to the 254th item it bails. is there a limit to a batch.
On Error GoTo Err_cmdProcessAll
Dim cn As ADODB.Connection
Dim rs As ADODB.Recordset
Dim strTableName As String
Dim strSql As String
'
Set cn = New ADODB.Connection
cn.Open "Provider=sqloledb; " & _
"Data Source=" & "BLD-FS-SQLVS04\PRDINST4" & ";" & _
"Initial Catalog=" & "HNFS_NetProv" & ";" & _
"Integrated Security=SSPI;"
cn.CursorLocation = adUseServer
Dim strSortField As String
Dim additionalwhere As String
If cboValue = "pc3Claims" Then
strTableName = "Seq3_PendedClaims_Ranked"
strSortField = "DaysSinceReceivedClaim"
' additionalwhere = " AND (member_eligibility_ud Not Like '%Program%')
strSql = "Select * " & _
"FROM " & strTableName & _
" WHERE (Complete Is Null) And (AssignedTo Is Null)" & additionalwhere & _
" ORDER BY cast( " & strSortField & " as int )" & strSort
ElseIf cboValue = "pc3ContractAssignments" Then
strSortField = "date"
additionalwhere = ""
strSql = "Select * " & _
"FROM " & strTableName & _
" WHERE (Complete Is Null) And (AssignedTo Is Null)" & additionalwhere & _
" ORDER BY CONVERT(varchar(10), CONVERT(datetime, [" & strSortField & "], 111), 121) " & strSort
End If
Set rs = New ADODB.Recordset
With rs
Set .ActiveConnection = cn
.Source = strSql
.LockType = adLockOptimistic
.CursorType = adOpenKeyset
.CursorLocation = adUseClient
.Open
End With
'make change to above to include
Dim i As Long
Dim j As Long
Dim strAssignAssociate As String
Dim lngAllocAmt As Long
For i = 1 To ListView6.ListItems.Count
If ListView6.ListItems(i).Checked Then
strAssignAssociate = ListView6.ListItems(i).SubItems(1)
Debug.Print strAssignAssociate
lngAllocAmt = ListView6.ListItems(i).Text
For j = 1 To lngAllocAmt
Debug.Print rs.Fields("AssignedTo")
rs.Fields("AssignedTo") = strAssignAssociate
Debug.Print rs.Fields("AssignedTo")
rs.MoveNext
Next j
End If
Next i
rs.UpdateBatch
MsgBox "All Finished", vbOKOnly, "Inventory Control"
Set rs = Nothing
Set cn = Nothing
I found the problem. I am using a non-keyed file. I found that I had duplicates in the file. this has been rectified and the above code works fine.
Hey guys I have to extract some values from my DB and put them on my textbox. There's a problem at :
TextBox1.Text = TextBox1.Text & DR.Item("id") & Space(3) & DR.Item("Nume") & Space(3) & DR.Item("COUNT(pontaj.prezente)")
Error in VB:
This is how my select looks like:
Dim dbCon = New MySqlConnection("Server = localhost;Database = users; Uid=root; Pwd = password ")
'SELECT users1.id,users1.Nume, COUNT(pontaj.prezente) FROM users1, pontaj WHERE users1.id = pontaj.id
Dim strQuery = "SELECT users1.id,users1.Nume, COUNT(pontaj.prezente)" & _
"FROM users1, pontaj "
Dim SQLCmd = New MySqlCommand(strQuery, dbCon)
' Pwd = password
' Open
dbCon.Open()
Dim DR = SQLCmd.ExecuteReader
TextBox1.Text = TextBox1.Text & DR.Item("id") & Space(3) & DR.Item("Nume") & Space(3) & DR.Item("COUNT(pontaj.prezente)") & vbCrlf
While DR.Read
End While
'Close
DR.Close()
dbCon.Close()
Well, the error is clear, you cannot access the fields of a DataReader before calling Read.
The call is required to position the reader on the first record returned by the query and then to advance on the subsequent records until you reach the end of the returned records.
Also the syntax for your query seems incorrect and the way you reference the third column of your query
Dim dbCon = New MySqlConnection(............)
Dim strQuery = "SELECT users1.id,users1.Nume, COUNT(pontaj.prezente) as countPrezente " & _
"FROM users1 INNER JOIN pontaj ON users1.id = pontaj.id " & _
"GROUP BY users1.id, users1.Nume"
Dim SQLCmd = New MySqlCommand(strQuery, dbCon)
dbCon.Open()
Dim DR = SQLCmd.ExecuteReader
' If Read returns true then you have one or more record to show'
While DR.Read()
TextBox1.Text = TextBox1.Text & _
DR.Item("id") & Space(3) & _
DR.Item("Nume") & Space(3) & _
DR.Item("countPrezente") & vbCrlf
End While
DR.Close
dbCon.Close
Looking at your previous question, the Foreign Key between users1 and pontaj is named id, so I have used an explicit join between the two tables to link the records from the two tables
I have very little experience with Access Databases however I have wrote a similar VBA macro in excel. I am trying to copy rows from one .mdb file into the exact same table on a different .mdb file. However I would like it to only import it if it does not already exsist. Could someone please advise me the best way to go about this and maybe some code I can use and modify? I have already looked around stack overflow and can't seem to find any examples that work.
There are 8 different tables and inside these a few hundred rows. with maybe 5-20 columns.
If the script could be made inside VBS this would be ideal, as it would allow me to run the updates without loading into access.
Thanks for any help or advice,
Simon
EDIT -
Zev's answer seems to do the job however I am getting this error, also the MDB inside site2 is the one I am copying from and putting it into site1
Error: Expected end of statement
Code: 800A0401
Line: 17
Char: 13
Code (saved as "update.vbs"):
Dim eng
Set eng = CreateObject("DAO.DBEngine.120")
Set dest = eng.OpenDatabase("C:\Users\simon\Documents\garden games redesign\import script\Site1\ActinicCatalog.mdb")
Sub CopyTable()
Dim rs
Set rs = dest.OpenRecordset("Person")
Dim sWhere
For Each fld In rs.Fields
sWhere = sWhere & " AND " & fld.Name & " <> t1." & fld.Name
Next
sWhere = Mid(sWhere, 6)
Dim sql: sql= _
"INSERT INTO Person " & _
"SELECT * " & _
"FROM Person AS t1 IN ""C:\Users\simon\Documents\garden games redesign\import script\Site2\ActinicCatalog.mdb"" " & _
"WHERE " & sWhere
dest.Execute(sql)
End Sub
Edit for more info:
\Site1\ActinicCatalog.mdb - is destination database
\Site2\ActinicCatalog.mdb - is original database
These databases have about 20 columns
Here is an example to get you started. It copies the content of [Table1] of the current database to [Table1] of a second database.
Option Compare Database
Option Explicit
Sub copyTables()
'Open source database
Dim dSource As Database
Set dSource = CurrentDb
'Open dest database
Dim dDest As Database
Set dDest = DAO.OpenDatabase("C:\Users\Admin\Desktop\DBdest.accdb")
'Open source recordset
Dim rSource As Recordset
Set rSource = dSource.OpenRecordset("Table1", dbOpenForwardOnly)
'Open dest recordset
Dim rDest As Recordset
Set rDest = dDest.OpenRecordset("Table1", dbOpenDynaset)
'Loop through source recordset
While Not rSource.EOF
'Look for record in dest recordset
rDest.FindFirst _
"Field1 = '" & rSource.Fields("Field1") & "' AND " & _
"Field2 = " & rSource.Fields("Field2")
'If not found, copy record - Field1 is text / Field2 is numeric
If rDest.NoMatch Then
rDest.AddNew
rDest.Fields("Field1") = rSource.Fields("Field1")
rDest.Fields("Field2") = rSource.Fields("Field2")
rDest.Update
End If
'Next source record
rSource.MoveNext
Wend
'Close dest recordset
rDest.Close
Set rDest = Nothing
'Close source recordset
rSource.Close
Set rSource = Nothing
'Close dest database
dDest.Close
Set dDest = Nothing
'Close source database
dSource.Close
Set dSource = Nothing
End Sub
I would suggest using an SQL statement if possible. From VBScript using DAO/ACE:
Dim eng
Set eng = CreateObject("DAO.DBEngine.120")
Set dest = eng.OpenDatabase("path\to\destination\database.accdb")
Using ADO:
Dim conn
Set conn = CreateObject("ADODB.Connection")
With conn
.Provider = "Microsoft.ACE.OLEDB.12.0"
.ConnectionString = "Data Source=""path\to\destination\database.accdb"";"
.Open
End With
The SQL statement would be something like this:
INSERT INTO Table1
SELECT *
FROM Table1 AS t1 IN "path\to\source\database.accdb"
WHERE Table1.Field1 <> t1.Field1
and executed like this:
Dim sql = _
"INSERT INTO Table1 " & _
"SELECT * " & _
"FROM Table1 AS t1 IN "path\to\source\database.accdb" " & _
"WHERE Table1.Field1 <> t1.Field1"
'Using DAO or ADO
dest.Execute sql
Considering that each table has a variable number of columns, you might have to generate the WHERE expression dynamically:
Sub CopyTable(tablename)
Dim rs
Set rs = dest.OpenRecordset(tablename)
'if using ADO:
'Set rs = conn.Execute(tablename)
Dim sWhere
For Each fld In rs.Fields
sWhere = sWhere & " AND " & fld.Name & " <> t1." & fld.Name
Next
sWhere = Mid(sWhere, 6)
Dim sql
sql = _
"INSERT INTO " & tablename & " " & _
"SELECT * " & _
"FROM " & tablename & " AS t1 IN ""path\to\source\database.accdb"" " & _
"WHERE " & sWhere
dest.Execute(sql)
End Sub
Update
If you are only using one column to determine whether the record exists, the SQL statement should look like this:
INSERT INTO Table1
SELECT *
FROM Table1 AS t1 IN "path\to\source\database.accdb"
LEFT JOIN Table1 ON t1.FirstField = Table1.FirstField
WHERE Table1.FirstField IS NULL
and CopyTable like this:
Sub CopyTable(tablename)
Dim rs
Set rs = dest.OpenRecordset(tablename)
'if using ADO:
'Set rs = conn.Execute(tablename)
Dim field0Name
field0Name=rs.Fields(0).Name
Dim sql
sql = _
"INSERT INTO " & tablename & " " & _
"SELECT * " & _
"FROM " & tablename & " AS t1 IN ""path\to\source\database.accdb"" " & _
"LEFT JOIN " & tablename & " ON t1." & field0Name & "=" & tablename & "." & field0Name & " " & _
"WHERE " & tablename & "." & field0Name & " IS NULL"
dest.Execute(sql)
End Sub