Run one MS Access SQL script on a particular Table chosen by user - sql

I have a MS Access 2016 database (*.accdb) with 20+ Tables. Fields in each of them vary slightly from Table to Table. I've no VBA experience, so I'm sticking only to the SQL query below (redacted).
SQL script
myvar below is the parameter I'd like to be prompted when the script is run so that I enter the Table I want the changes applied to.
PARAMETERS
[myvar] TableID;
UPDATE
[myvar]
INNER JOIN
Excel_Data ON [myvar].[Part Number] = Excel_Data.[Part Number]
SET
[myvar].[Value] = '?',
[myvar].Description = Excel_Data.Description,
[myvar].[Ref] = '?'
.
.
.
WHERE
[myvar].Description Is Null;
Output
Error message:
Too few parameters. Expected 0.
What I need
I prefer a solution for above in a SQL script form as above, not involving VBA, preferably. I'd like to enter the Table name when prompted so the script knows which table to UPDATE. FYI: The PARAMETERS work when it is not a Table as I've shown in my script above.
Help/advise is highly appreciated.
EDIT 1
Since it seems not possible to use parameters as Table names, could you suggest a VBA solution? A sample code, perhaps?

As said in the comments, you can't really solve this without VBA.
You can store your SQL query in a string, and use a placeholder to indicate the tablename. Then get the tablename using an inputbox and replace the placeholder with the tablename.
Dim sqlString As String
sqlString = "UPDATE [%Placeholder%] " & vbCrLf & _
"INNER JOIN Excel_Data ON [%Placeholder%].[Part Number] = Excel_Data.[Part Number] " & vbCrLf & _
"SET [%Placeholder%].[Value] = '?', " & vbCrLf & _
...
"WHERE [%Placeholder%].Description Is Null;"
sqlString = Replace(sqlString, "%PlaceHolder%", InputBox("Enter a tablename"))
CurrentDb.Execute sqlString
In a more mature solution, I'd create a form with a combobox containing all available table names, and add a function to sanitize tablenames (replace "]" with "]]")

Related

Retrieve Data from SQL with input from table

I have a table in excel, with range : Sheets("Sheet1").Range("d4:d215"). These data are similar to PS.WELL in the server.
From that table, I want to retrieve data using this code (other SQL requisite has been loaded, this is the main code only):
strquery = "SELECT PS.WELL, PS.TYPE, PS.TOPSND " & _
"FROM ISYS.PS PS " & _
"WHERE PS.WELL = '" & Sheets("Sheet1").Range("D4:D215") "' AND (PS.TYPE = 'O' OR PS.TYPE = 'O_' OR PS.TYPE = 'GOW') " & _
"ORDER BY PS.WELL"
Unfortunately it didn't work. Can anyone help me how to write the code especially in the 'where' section?
You have to iterate through each item in the range and concatenate the results to a string variable so the contents look like this
'val1','val2','val3'
Then you have to adjust your query code to use the IN operator instead of equals operator. Let's say the string is concatenated to a variable called myrange.
"WHERE PS.WELL IN (" & myrange & ") AND ...
I have solved the problem. The key is to make 2 function of SQL:
to read and write each input
to count number of output per input (an input can have 0, 1, or more output).
then, just call using procedure

MS Access SQL - Update field in one table with a count from another table

I have a table called 'FilesUploaded' which has a summary of all files uploaded to my access DB. I want to add a field in here that contains the count of all errors from another table.
My FilesUploaded table contains a field called 'FileName' which has
the full name of the file.
I want to get a count of all records in table1 where the 'ValidityCheck' field contains 'Error'. Table1 also contains a field called 'Name_of_Report' which has the file name which will match back to the FilesUploaded table.
The 'vFileName' variable will contain what is in both the 'Filename' field and the 'Name_of_Report' field
The below is the code I have tried using, but it says this type of join is not allowed and I have no idea what other way I can achieve this.
Call RunSQL("UPDATE FilesUploaded " & _
"LEFT JOIN (SELECT table1.Name_of_Report, Sum(IIf([table1].[ValidityCheck] Like '*Error*',1,0)) AS ErrorCount FROM table1 GROUP BY table1.Name_of_Report) AS temp on temp.Name_of_Report = FilesUploaded.FileName " & _
"SET " & _
"FilesUploaded.[ErrorCount] = temp.ErrorCount " & _
"WHERE FilesUploaded.[FileName] = '" & vFileName & "' ")
Does anybody know a different way can update the FilesUploaded table with a count of the ValidityCheck field from the Table1 table?
In MS Access, UPDATE...JOIN requires its analogous SELECT...JOIN to be updateable. Aggregate queries using SUM are not updateable queries. Therefore, consider domain functions like DSum.
Additionally, consider a stored query and call it in VBA with parameterization via QueryDefs. Do note the use of ALIKE to use % for wildcards in case you need to run query outside of the MS Access GUI such as in ODBC or OLEDB connections where * is not recognized.
SQL (save as a stored query)
PARAMETERS paramFileName TEXT;
UPDATE FilesUploaded f
SET f.[ErrorCount] = DSUM("*", "table1",
"[ValidityCheck] ALIKE '%Error%' AND [Name_of_Report]='" & f.[FileName] & "'")
WHERE f.[FileName] = [paramFileName];
VBA (run query without string concatenation)
Dim qdef As QueryDef
Set qdef = CurrentDb.QueryDefs("mySavedQuery")
qdef![paramFileName] = vFileName ' BIND PARAM VALUE
qdef.Execute ' RUN ACTION QUERY
Set qdef = Nothing

Outputting the result of an SQL query into a text box

I'm creating a form that displays information about an individual that is taken from two tables when a name is entered by the user. I want the fields to be output into they're own text boxes. My code looks similar to what's below.
When I run the code it displays the literal query "SELECT name etc..." in the textbox. I saw Dlookup works for textboxes but to my understanding it doesn't work well with more than one table. Any advice would be greatly appreciated!
PS I'm a VBA/access newbie
Dim SQL, SearchInput As String
SQL = "SELECT name" & _
"FROM tablename INNER JOIN othertablename ON tablename.name = othertablename.name" & _
"WHERE tablename.name LIKE ""*" & SearchInput & "*""
Me.txtbox = SQL
I'm pretty sure this is a duplicate, but it's faster to answer than hunt for the other posts.
You need to declare a recordset and assign the data returned from the select statement to it. This will leave you with something very similar to an array. After that you need to just line up the array element to the positions of the columns. IE. rs(0)=name in the select statement above.
Dim rs As Recordset
Dim SQL As String, SearchInput As String
SQL = "SELECT name " & _
"FROM tablename INNER JOIN othertablename ON tablename.name = othertablename.name " & _
"WHERE tablename.name LIKE ""*" & SearchInput & "*""
Set rs = CurrentDb.OpenRecordset(strSQL, dbOpenSnapshot)
Me.txtBox = rs(0)
That should work.
Since you are new to MS Access & VBA in general, I'll propose a solution which avoids VBA entirely.
In your current code, I assume that SearchInput is sourcing its value from another control on your form.
I would suggest creating a new saved query (called it MyQuery) with the following SQL:
select table2.name from table1 inner join table2 on table1.name = table2.name
Then, in the Control Source for your textbox, use a DLookup expression with the following arguments:
=dlookup("[name]", "MyQuery", "table1.name like '*" & [SearchInput] & "*'")
Here, [SearchInput] refers to the name of the control on your form containing the search criteria.

Access 2007 VBA: Returning data from SQL statements that use multiple variables

I am working on a form that is meant to analyze financial data ahead of an insurance policy renewal. It needs to pull various premium and claim $$ totals from the tables, and insert them into the form. From there, it will run some calculations with them, but that should be the easy part. Where I'm struggling is the SQL statements to get the data, in the first place.
After narrowing it down a bit, I've found that the problem is the code is putting the SQL statement into the field on the form, instead of the answer the SQL statement should be providing. I have tried multiple things I've seen online, and can't figure out how to resolve this.
One of the SQL statements reads like this:
L12W = "SELECT Sum(tblActPrem.APWrit) AS SumOfAPWrit FROM tblActPrem " _
& " WHERE tblActPrem.EntID = '" & Me.ctlActEntID & "' " _
& " AND tblActPrem.PolNum = '" & Me.ctltblRnwlTrack_PolNum & "'" _
& " AND tblActPrem.APDate BETWEEN #" & L12M & "# AND #" & Me.ctlRnwAnalysisDt & "#;"""
It should be totalling premium data from the table, where the policy number and account number match what's on the form, and between the selected dates, and putting that total into the field on the form. Instead, I get this on the form:
SELECT Sum(tblActPrem.APWrit) AS SumOfAPWrit FROM tblActPrem WHERE tblActPrem.EntID = '1235' AND tblActPrem.PolNum = 'Policy1' AND tblActPrem.APDate BETWEEN #1/1/2014# AND #1/1/2015#;"
That is exactly how the statement should be running, but can anyone tell me how to make the leap from the statement, to the data?
Thank you!
Consider using DLookup or DSum in the control source of the form's field.
DLookup Solution
First, change your VBA SQL query into a stored SQL Query (notice quotes and # symbols are not necessary when referencing form controls):
SELECT Sum(tblActPrem.APWrit) AS SumOfAPWrit
FROM tblActPrem
WHERE tblActPrem.EntID = Forms!<yourformname>!ctlActEntID
AND tblActPrem.PolNum = Forms!<yourformname>!ctltblRnwlTrack_PolNum
AND tblActPrem.APDate BETWEEN Forms!<yourformname>!L12M
AND Forms!<yourformname>!ctlRnwAnalysisDt
And then in the form field textbox's control source use the DLookUp function (no criteria argument is needed since this should return only one value).
= DLookUp("SumOfAPWrit", "<yournewqueryname>")
DSum Solution
Alternatively, you can change the entire SQL statement into a DSum but notice how long the criteria (WHERE statement) would have to be.
= DSum("APWrit", "tblActPrem", "EntID = Forms!<yourformname>!ctlActEntID
AND PolNum = Forms!<yourformname>!ctltblRnwlTrack_PolNum
AND APDate BETWEEN Forms!<yourformname>!L12M AND Forms!<yourformname>!ctlRnwAnalysisDt")

Vba requery parameter syntax

I need to set the parameter for a requery command, but I canĀ“t find the correct syntax.
tbTreinamentosConc.Requery Profissional = prof
tbTreinamentosConc refers to table Trn_Done, which has the column Profissional, among the others and prof is the parameter I want to be used when searching in the table Trn_Done, in the field Profissional.
What is the correct way to get it working?
Thanks in advance!
A requery will simply update the information in a given object, you can't pass arguments to it. You can however write an SQL statement to query for something specific...
Dim strSQL As String
strSQL = "SELECT * " & _
"FROM tbTreinamentosConc "
"WHERE Profissional ='" & txtInput & ";"
DoCmd.RunSQL strSQL
txtInput will be a text box on your field that you can enter the 'prof' parameter into; This should work.