Errors in UPDATE query - VB6 DAO Access - ms-access

A simple UPDATE query with INNER JOIN is causing me problems, using VB6 and DAO on an Access .MDB database.
I thought it would be simple, but whatever changes I make generate errors.
My query is:
UPDATE work
INNER JOIN emp ON work.ref = emp.ref
SET work.code1 = emp.code1
This generates run-time error 3075 Syntax error in query expression 'work.ref = emp.ref'.
I get a similar error with:
UPDATE work w
INNER JOIN emp ON w.ref = emp.ref
SET w.code1 = emp.code1
and
UPDATE [work] w
INNER JOIN emp ON w.ref = emp.ref
SET w.code1 = emp.code1
and also if I use alias e for table emp.
I cannot use a FROM clause, which is not supported in Access (Thanks though #MarkKram)
I have to use DAO 3.51 (old!) in VB6, which cannot easily be changed.
I have tried square brackets around the first reference to work as in UPDATE [work] (as I need this in a simple SELECT * FROM [work]) as well as various combinations with and without square brackets around table names and column names. But still it fails.
Do you have any suggestions please?
Dim ws As DAO.Workspace
Dim DB As DAO.Database
Dim szSQL As String
Set ws = gWS
Set DB = gWS.OpenDatabase(WorkFile)
szSQL = "UPDATE work INNER JOIN emp ON work.ref = emp.ref SET work.code1 = emp.code1 WHERE work.trancode = 'P'"
DB.Execute szSQL
Set DB = Nothing
Set ws = Nothing

Try this:
UPDATE work, emp
SET work.code1 = emp.code1
WHERE work.ref = emp.ref AND work.transcode ='P'

Related

MS Access VBA improve script

I have this code in MS Access (I did it in VBA becasue I didn't find the way to create a procedure in Access). What it does is simple, it takes a field form a table and replace the value in another table where the ID is the same.
How can I get this faster? It is currently taking 8 minutes more or less to get it done (processor is always under 20%, so it is not about processor power).
Set rst = CurrentDb.OpenRecordset("Tab_personal_2")
rst.MoveFirst
DoCmd.SetWarnings False
Do Until rst.EOF
DoCmd.RunSQL ("UPDATE Tab_personal_3 SET RFC = '" & rst("RFC") & "' WHERE Id = " & rst("Id"))
rst.MoveNext
Loop
You should be able to do this in a single query:
UPDATE Tab_personal_3 t3
INNER JOIN Tab_personal_2 t2 ON t2.ID = t3.ID
SET t3.RFC = t2.RFC
Of course, you can execute this query through VBA, if you wish. But storing the query allows Access to store the execution plan, and increase the speed on the query.
I believe a single update query will work if the tables share an ID field:
UPDATE Tab_personal_3 INNER JOIN Tab_personal_2 ON Tab_personal_3.ageing_collection = Tab_personal_2.Id SET Tab_personal_3.RFC = Tab_personal_2.RFC;

Formatting a listbox alternative [duplicate]

I am using the below SQL, it works fine if I run it from query builder but once I have put it in VBA it throws out an error:
Code:
With CurrentDb.CreateQueryDef("", "SELECT [_tbl_Structure].[User Name], tbl_Genesys_Daily.Field32, [_tbl_Structure].[Supervisor Emp Num], [_tbl_Structure].Supervisor FROM _tbl_Structure RIGHT JOIN tbl_Genesys_Daily ON [_tbl_Structure].[User ID] = tbl_Genesys_Daily.Field5 WHERE ((([_tbl_Structure].Supervisor)=?));")
.Parameters(0) = [Forms]![frm_Manager_Stats_NEW]![Text279]
Set lvxObj = AvailabilityCap.Object
Set rs = CurrentDb.OpenRecordset(strSQL, dbOpenDynaset)
End With
Error:
Too few parameters. Expected 1. (Runtime 3061)
Any help on understanding why this works for one but not another is appreciated
Form- and report-based parameters are only available in the GUI context (queries run using the GUI, forms, reports, macros and DoCmd.RunSQL). You're probably executing this through CurrentDb, and need to use a querydef instead.
With CurrentDb.CreateQueryDef("", "SELECT [_tbl_Structure].[User Name], tbl_Genesys_Daily.Field32, [_tbl_Structure].[Supervisor Emp Num], [_tbl_Structure].Supervisor FROM _tbl_Structure RIGHT JOIN tbl_Genesys_Daily ON [_tbl_Structure].[User ID] = tbl_Genesys_Daily.Field5 WHERE ((([_tbl_Structure].Supervisor)=?));")
.Parameters(0) = [Forms]![frm_Manager_Stats_NEW]![Text279]
Set rs = .OpenRecordset
End With
You can learn more about the different types of parameters, and when to use which one, in this answer

Prepared Statement in mysql through excel VBA

I have worked on a prepared statement in Mysql, which dynamically creates week columns based on the current date. It works seamlessly when I run the query in Toad for Mysql, I'm having enormous problems running the query when I am trying to convert the query to a string in VBA......I get an error stating I have a problem with the syntax near etc with the sql. The error is created in every part of the sql despite the fact the string looks fine. I subbed in for " with chr(34), or ' with chr(39) and still I get an error with the sql syntax. I have also tried to avoid these string problems by importing the code below which imports the .sql file to no avail.
Sub TopAway()
Dim Cnn As Object
Dim Rst As Object
Dim ConnectionString, SqlTextFile, SqlStatement As String
Set Cnn = CreateObject("ADODB.Connection")
Set Rst = CreateObject("ADODB.Recordset")
Application.ScreenUpdating = False
ThisWorkbook.Sheets("Summary").Range("A2:T3000").ClearContents
ConnectionString = "Driver={MySQL ODBC 5.3 Unicode Driver};Server = 10.1.1.201; Database = cms; Uid = root; Pwd = something;"
Cnn.Open ConnectionString
Cnn.CommandTimeout = 900
SqlTextFile = "C:\Users\adam\Desktop\WORK FOLDER\Tony Project\Analysis Projects\Away_No_Stock\Dynamic_Away.sql"
Debug.Print SqlTextFile
Dim hFile As Long
hFile = FreeFile
Open SqlTextFile For Input As #hFile
SqlStatement = Input$(LOF(hFile), hFile)
Close #hFile
Debug.Print SqlStatement
Rst.Open SqlStatement, Cnn '<-- This is where the code fails
Sheets("Summary").Range("B3").CopyFromRecordset Rst
End Sub
The SQL code is below.....
SELECT
GROUP_CONCAT(DISTINCT
CONCAT("SUM(IF((part_id IN (265,302,647) OR notes REGEXP ('away|unfit|unavailable|bus away|night')) && WEEKOFYEAR(job_engineerdate) = '", WEEKOFYEAR(job_engineerdate) , "' , 1 ,0)) AS '", WEEKOFYEAR(job_engineerdate), "'")
)
INTO #answers
FROM (
SELECT DISTINCT (job_engineerdate)
FROM job j
ORDER BY (job_engineerdate) ASC
) A
WHERE job_engineerdate >= CURDATE() - INTERVAL 112 DAY AND job_engineerdate <= CURDATE();
SET #query = CONCAT("SELECT customer_name, garage_name, ", #answers, "
FROM (
SELECT c.customer_name, g.garage_name, j.id, jp.part_id, jn.notes, j.job_engineerdate
FROM job j
INNER JOIN vehicle v ON j.job_vehicleid = v.id
INNER JOIN garage g ON v.garage_id = g.id
INNER JOIN customer c ON g.customer_id = c.id
INNER JOIN fault_type ft ON j.job_fault = ft.id
INNER JOIN job_parts jp ON j.id = jp.job_id
INNER JOIN part p ON p.id = jp.part_id
INNER JOIN job_notes jn ON j.id = jn.job_id
INNER JOIN users u ON j.job_engineer = u.id
WHERE
c.customer_group IN (13) AND
j.deleted = 0
AND j.job_engineerdate >= CURDATE() - INTERVAL 112 DAY
GROUP BY
v.vehicle_fleet_number, v.id, j.id, jp.part_id, jn.id
ORDER BY customer_name, garage_name
) AS T
GROUP BY customer_name, garage_name
ORDER BY 18 DESC
LIMIT 15")
;
PREPARE stmt FROM #query;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
I have no idea how to get this working through excel, if anybody has any ideas, it would be very much appreciated!! I have spent a long time looking on the web for answers but have not been able to find any solutions to this problem. Thanks in advance!
I tackle also with this kind of problem how to translate an sql prepared statement in Excel (VBA), finally I went through with writing a routine in VBA to build the same sql statement as it would be build by the prepared statement.
At the end a prepared statement is a "procedure" you should have no problem translating it in a VBA code.
Hope it helps you (even if I didn't manage to write the VBA code relevant to your case)...

Convert a databound combobox's data to ProperCase in VB 2010

In VB 2010 I'm trying to show the DisplayMember in ProperCase without modifying my existing MySQL tables.
A snippet of my code looks like this:
Dim sql0 As String = "SELECT business, customer_id FROM customers WHERE cab = '1'"
Dim data0 As New MySqlDataAdapter(sql0, main.conn)
Dim ds0 As New DataSet
ds0.Clear()
data0.Fill(ds0, "customers")
cmb_company.DataSource = ds0
cmb_company.DisplayMember = "customers.business"
cmb_company.ValueMember = "customers.customer_id"
Ive tried something like this:
cmb_company.DisplayMember = StrConv("customers.business_name", VbStrConv.ProperCase)
but this only changes the case of the part in quotes, and not the actual returned values. I also tried querying from MySQL like this:
"SELECT UPPER(business), customer_id FROM customers WHERE cab = '1'"
but this fails to return the "business" field..
I'd love it if my combobox had proper case without changing everything.
I appreciate any suggestions!
Use the second one, but use an alias like this:
"SELECT UPPER(business) AS Business, customer_id FROM customers WHERE cab = '1'"
MySQL documentation:
A select_expr can be given an alias using AS alias_name. The alias is
used as the expression's column name and can be used in GROUP BY,
ORDER BY, or HAVING clauses. For example:
SELECT CONCAT(last_name,', ',first_name) AS full_name FROM mytable
ORDER BY full_name;
It seems a bit silly to use a while loop to achieve this especially after filling the table with an adapter. I suppose I could have just skipped the .fill and added the items manually through the loop, all while ProperCasing them. Anyway, here is my code:
Dim sql1 As String = "SELECT * FROM table"
Dim data1 As New MySqlDataAdapter(sql1, main.conn)
Dim ds1 As New DataSet
ds1.Clear()
data1.Fill(ds1, "table")
cmb_buyout.DataSource = ds1
Dim i As Integer = 0
While i < ds1.Tables(0).Rows.Count
Dim name As String = StrConv(ds1.Tables(0).Rows(i).Item(1).ToString, VbStrConv.ProperCase)
ds1.Tables(0).Rows(i).Item(1) = name
i += 1
End While
cmb_buyout.DisplayMember = "table.buyoutType"
cmb_buyout.ValueMember = "table.id"
To anyone trying to accomplish this, it is probably simpler to just change the case on the entries in the DB. I might just end up doing this!

Update a single table based on multiple tables - appears to works MySql not ACCESS 2003

Mysql Version Works
UPDATE results SET rCARRIER = (
SELECT cellCarrierName
FROM tblImportedTempTable, user, cellCarrier
WHERE
userEmployeeNumber = tblImportedTempTable.EMPLOYEENUMBER
AND userId = results.rUserId
AND results.rPHONENUMBER = tblImportedTempTable.PHONENUMBER
AND CARRIER = cellCarrierId )
I have written this sql that works fine in MySql(above) and fails in access 2003(below) any suggestions? Is one or both of the 2 nonstandard sql? Does Access hav an admin problem?
Sorry the field and table names are diferent this is the ACCESS version.
Access version
UPDATE tblWorkerPhoneNumber SET tblWorkerPhoneNumber.PhoneCarrier = (
SELECT PhoneCarrierType.CarrierName
FROM tblImportedPhoneCarrier, tblWorkerMaster, PhoneCarrierType
WHERE
tblWorkerMaster.EmployeeNumber = tblImportedPhoneCarrier.Emp
AND tblWorkerMaster.WorkerID = tblWorkerPhoneNumber.WorkerID
AND tblWorkerPhoneNumber.PhoneNumber = tblImportedPhoneCarrier.Cell
AND tblImportedPhoneCarrier.CarrierCode = PhoneCarrierType.CarrierID )
Error Message
Operation must use and updateable query
Thanks
In MS Access, something like this:
UPDATE tblWorkerPhoneNumber
INNER JOIN tblWorkerMaster ON tblWorkerMaster.WorkerID = tblWorkerPhoneNumber.WorkerID
INNER JOIN tblImportedPhoneCarrier ON tblWorkerPhoneNumber.PhoneNumber = tblImportedPhoneCarrier.Cell
INNER JOIN PhoneCarrierType ON tblImportedPhoneCarrier.CarrierCode = PhoneCarrierType.CarrierID
SET tblWorkerPhoneNumber.PhoneCarrier = PhoneCarrierType.CarrierName
WHERE tblWorkerMaster.EmployeeNumber = tblImportedPhoneCarrier.Emp
(Might need to change the join conditions; I'm not familiar with your schema)