hey guys, could someone show me the simple update query through vb? I need to add new fields to the table (just 3) and add a couple text boxes on a form so that users can add some additional data relative to the record (which is already what this form is based on).
So the first form I have is a form that populates a list, when the user double clicks on a selection from that list, it opens a new form, so that the ID of the the table that is tied to this form that I need to add the these text boxes on (all the combo boxes and text boxes relative to one record are tied to the active form at this point, however there are all unbound. On a button click there is already vb that saves the information to the table). I did not create this however, it was built by someone who is not there anymore, and apparently is better than I at this stuff. My problem is that there is soooo much vb that checks for records, and various sql statements based on case, that I cannot decipher it to its simplest form.
So I was looking for a simple example of an update sql statement in vb so I can try to break this apart.
I need it to update the record based on the ID: sql WHERE RecordID = me.RecordID
I actually thought I knew how to do this based on examples, however every time I try, then try to run on button click, I get a run-time error of SYNTAX error, and the debug just highlights the db.execute(sql) part. So I tried to get the resulting immediate window of the sql statement, and it looks fine to me:
UPDATE tblMain
SET [Name] = "John Doe",
[DATE] = #9/30/2009#,
[TYPE] = "TypeA",
WHERE RecordID = 958;
Can I update a table without accounting for every field in the table (because this one has about 15 plus the new 3, so I am ignoring about 14 fields here, but I do not want to alter those anyway???
So as always, I appreciate the help yall!! Thanks!
EDIT:
Sorry I always forget this....I was actaully trying it DAO....
Dim db as DAO.Database
Dim sql as String
set db = CurrentDb
etc
You were thaaat close! You have a simple extra comma after your last column. Get rid of it and it works fine.
UPDATE tblMain SET
[Name] = "John Doe",
[DATE] = #9/30/2009#,
[TYPE] = "TypeA"
WHERE RecordID = 958;
Yes, you can absolutely update only a few columns rather than all of them. That is a best practice, BTW.
Finally, It's considered bad practice to name your columns after reserved words like "Name" and "Date", but I know you inherited this.
You were wise to include Debug.Print sql in your code. bpayne already pointed out the extra comma in your SQL statement.
I want to point out another trouble shooting technique you may find useful to debug SQL statement problems.
Copy the statement from the Immediate Window, and paste it into the SQL View of a new query. Modify the query in the query designer until you can get it working, then revise your VBA code to generate a matching SQL statement.
In this case you might not have noticed the extra comma. However, you could create another new query and build the UPDATE statement from scratch in the query designer. After getting that one working, you could compare its SQL View to the failing query.
Related
I'm working on a selection query in my Access database. in one of my columns I wanted to have a drop-down list with selected data. Unfortunately nothing is showing, and I'm thinking about two Problems that can be responsible for this :
The selection wont show up until I link my query to a table where I can modify and select from the drop down list.
I made a mistake in developing but can't find anything about that mistake
Here is the details of whats going on :
What I want
This image is just the result of my query not linked to a table
What I have
Is an actual drop down list without any data in it (still talking about the result of the query not linked to a table in which modification can be made directly)
Here is What I did
Added the queries and tables I'm working on and then =>
Selected the column I wanted it to be a drop-down list and then added the following query after changing it to a drop down list
SELECT [SALARIE_nom] & " " & [SALARIE_prenom]
FROM (T_STATUT_EMPLOI INNER JOIN T_SALARIE_EMPLOI ON T_STATUT_EMPLOI.STATUT_EMPLOI_id = T_SALARIE_EMPLOI.SALARIE_EMPLOI_statut_id) LEFT JOIN R_Select_Salarie ON T_SALARIE_EMPLOI.SALARIE_EMPLOI_salarie_nni = R_Select_Salarie.SALARIE_NNI
WHERE (((T_STATUT_EMPLOI.STATUT_EMPLOI_statut) Like "*validé*") AND ((T_SALARIE_EMPLOI.SALARIE_EMPLOI_Entreprise) Like "*RTE*"));
if I run the sql query on it's own, it gives me the results I want but when trying to see this result in the final table (result table of my query) I got the blank drop-down list.
here is the result I get from executing the query alone :
So I think it's working.
Thank you in advance for reading my explanation and for your comments
I think that everything was fine, and that it was just a bug. After linking my query to a form I started seing the data in the drop-down list in both the form and query.
But I still Have one small issue which is :
Not being able to modify or choose from my drop-down List.
What I did
I created my form using Forms Assistant in access and then I chosed as data source my query. But I can't modify my form or anything could please suggest something to me.
Thank you !
I've been searching the internet for hours trying to figure out if the following is even possible:
To choose the AS400 query records directly from Excel.
I haven't found any solution or description of how this could be achieved, which makes me guess that it's simply not possible. However, I haven't seen anyone confirm that it is impossible.
So my question is: Is this possible? And if it is, could you point me in the right direction in order for me to start learning how to do it?
I know its possible to run a query from Excel, and then adding parameters via SQL statements, but in my case, this presents several problems that could be avoided by choosing the records before the query is executed.
Example:
I have a query with a column (lets call it ColVal) that can hold the values 1 and/or 2. In the AS400 program under the menu "Work with queries" and then "Choose records" I can specify which records the query should contain when it has run based on the value in ColVal. This means i can get three different situations (A, B and C) when i run the query:
A) The query only contains records where the value in ColVal is 1
B) The query only contains records where the value in ColVal is 2
C) The query contains records where the value in ColVal is either 1 or 2
The goal is to be able to choose which situation I want from Excel in order to circumvent opening and using the AS400 program.
However, using situation C and then editing the query in Excel with an SQL statement to mimic situation A or B is not an option, as this means the query still contains undesired records.
This whole thing boils down to the following: Is it even possible to run the query from Excel essentially changing the data it contains and not just outputting it to excel? If this is possible, is it then possible to pass a parameter to the AS400 system and use it to create situation A, B or C?
I hope this example makes sense.
Edit - New example
Say i have different customers A and B. I can open the AS400 program and run a query in which i have specified that I only want data on customer A. I can then open Excel and use filters (as Hambone described) on the query to determine which records I want to output. However, if I want to work with data from customer B, I have to open the AS400 again and run the query with different parameters. I would like to be able to "change" my dataset from customer A to B from Excel, without having to include both in my recordset and then filter out one of them.
I imagined this is doable if you could pass a parameter to the AS400. The AS400 then runs the query using this parameter as the criteria for which records should be stored in the query. This means that if the parameter is Customer B, then there is no way to acces data from customer A, without running the query through AS400 again.
Any ideas are greatly appreciated :)
Follow up to my comment, here is a quick primer on how to run an ODBC query directly in MS Excel using Microsoft Query. This is very different than Power Query, which you referenced, in that MS Query is standard with Excel -- it's not a plug-in. This is relevant because it means everyone has it. If you are deploying a solution to others, that's an important consideration.
To start an MS Query in Excel, go to the data tab, select "From Other Sources" -> "Microsoft Query."
A list of your ODBC connections will come up. Pick the one that you want and select "OK."
It may or may not ask you for a login (depending on which ODBC connection you use and how its configured).
The next part is important. MS Query is going to try to have you use its builder to create the query. If you have the SQL, skip this part. It's horrible. Click "Cancel" on the query wizard, and then click the "SQL" button to enter your own SQL. If you can, make sure the result set is small (like use where 1 = 2 in the query).
When MS Query returns results, click the button next to the SQL Button to have it return the results to the spreadsheet. It looks like a little door.
From here, any time you want to refresh the query, you can simply right-click the data table in Excel and select "refresh." Alternatively you can go to the data tab on the ribbon and select "Refresh."
By the way if you have linked pivot tables and charts, the "Refresh All" option will refresh those as well, in the correct order.
To edit your query at any time, right-click on the table in Excel, go to Table-External Data Properties:
Then Click on the Connection Properties icon (highlighted below)
Click on the second tab (Definition) and edit the SQL Directly.
Parameters can be declared simply by inserting a bare "?" in place of your literal.
In other words, if your query looks like this:
select *
from users
where user_id = 'hambone'
Just change it to:
select *
from users
where user_id = ?
Excel will prompt you for a user id before it runs the query. From here, you also have the option of putting the parameter value in a cell within the spreadsheet and having the query read it from there. You'll see these when you right-click the table and go to the "Parameters" menu option.
Let me know if this helps or is unclear.
-- EDIT 7/23/2018 --
To follow up on your latest edit, it is possible to handle the scenario you describe, where you want to be able to filter on a value, or if none is given, then not have a filter. You see this a lot when you present multiple filter options to the user and you want a blank to mean "no filter," which is obviously counter to the way SQL works.
However, you can hack SQL to still make it work:
select * from activities
where
(activity = ? or ? is null) and
(energy = ? or ? is null)
In this example you have to declare four parameters instead of two, two for each.
You might also have to play with datatypes, depending on the RDBMS (for example for numerics you might have to say ? = 0 instead of ? is null or even ? = '' for text).
Here is a working example where a single filter was applied on the query above and you can clearly see the second one did not have an impact.
Yes it's possible. You need to use an ODBC driver to connect to the AS400 and retrieve the data. The driver and documentation are Here
I have a simple database I am developing in MS Access 2010 where I have a form with a "view specific" command button and a "view all" command button. Both buttons will run a query: the specific one should apply a criteria to one of the fields, and the all one should run the query with no criteria, or with a * criteria in that field. There is another field that requires criteria for both queries, so essentially the specific button should run a query with two criteria and the all button should run a query with one criteria (or one and an * criteria). The query is a stored query I created via Design View. The "all" SQL statement is something to the effect of:
SELECT tableA.field1, tableA.field2, tableB.field1, tableB.field2
FROM tableA INNER JOIN tableB ON tableA.field3=tableB.field2
WHERE tableB.field1=True;
I want the specific query to run based off of an option chosen in a combo box on the form, so it's SQL statement should look the same, except the WHERE clause would change to:
WHERE tableB.field1=True AND tableB.field2=Forms!ViewQryResults!comboSelectSpecific;
Problem
My problem is that the specific query, I'll call it Query2, works as intended, but the all query, Query1, doesn't change the results viewed on the form. Neither query throws an error message, and it seems that the query is running again as the record total at the bottom of the screen goes away, and then comes back after the query finishes and gets a total number of records again.
Attempted Solutions
I have tried multiple different solutions to attempt to get it to work, none of which have.
I first tried to establish a parameter, but then Access prompts the user for the parameter value as soon as the form opens, which I do not want. If I simply declare the parameter using the parameter button in the ribbon in design view for the query, but do not assign it to a field as a criterion in the design grid, Access no longer prompts me for the parameter value, and I can assign its value via VBA, but then I do not know how to assign the parameter to a field criteria using VBA. My attempts throw errors that say Access doesn't recognize the name of my parameter.
I then tried altering the SQL string for the query and then requerying. I used text manipulation functions to find the WHERE clause, and replace it with a WHERE clause that has both criteria, then requeryed. To determine the proper context for the SQL string, I changed the query in Design View to do what I wanted, and then switched to SQL View and copied the SQL string that Access created to represent the query.
I then inserted a Debug.Print line to print the SQL string at each step, and compared them character by character and they match exactly, meaning the text manipulation is doing what it should be doing and creating the SQL strings correctly, or at least as Access would if I wasn't messing with them at all. I tried this from both directions, i.e. I made the stored query in the way it should be for one button, and then used code to change it for the other button, and then swapped, but neither method was successful in getting both queries to work. The basic code I tried for manipulating the SQL string is as follows:
Private Sub Query2_OnClick()
Dim d As Database
Dim q As Query
Dim strSQL As String
Dim strSQLSelectFrom As String
Dim strSQLWhereNew As String
Set d = CurrentDb
Set q = d.QueryDefs("Query2")
strSQL = q.SQL 'Saves original SQL statement
'Text Manipulations to create strSQLSelectFrom as just the SELECT and FROM portions
strSQLWhereNew = "tableB.field1=True AND tableB.field2=Forms!ViewQryResults!comboSelectSpecific;"
q.SQL = strSQLSelectFrom & strSQLWhereNew
DoCmd.Requery
Me.Refresh
Debug.Print q.SQL 'Verify text manipulations created SQL String I expect
q.SQL = strSQL 'Returns SQL to original statement
Debug.Print q.SQL 'Verify SQL statement properly returned to original statement
End Sub
This arrangement works to allow me to query specifics based on my combo box. When I click the other button, whose code just does a requery because the first button should reset SQL to the way it was, the results do not change. The query appears to run as indicated by the total records counter going away and coming back, but it never changes the results. If I go back and choose another option from my combo box, and query specific, the results update to the new specific selection.
Again, if I click the All Query button, the results remain based on the combo box selection. If I change the combo box selection, and then click All Query (which shouldn't care at all about the combo box because it isn't listed anywhere in the code for that button), the results change to the new selection, like both buttons are running specific queries. That part is the most puzzling, I can figure out why it is doing that.
I know a simple solution would be just to create a second query and stop trying to change one back and forth, but I really feel I am missing a fundamental piece that I am going to need to understand at some point, so I am really looking for that fundamental piece that will make this work.
IIUC - Simply change the form's RecordSource to point to needed saved query with .Requery:
Private Sub ViewAll_OnClick()
Me.Form.RecordSource = "Query1"
Me.Requery
End Sub
Private Sub ViewSpecific_OnClick()
Me.Form.RecordSource = "Query2"
Me.Requery
End Sub
Alternatively, you can keep the same query recordsource and filter form using DoCmd.ApplyFilter, assuming criteria controls are on same form requiring filtering. Any valid SQL WHERE clause can be used in second argument and even dynamically created.
DoCmd.ApplyFilter , "field1 = True AND field2 = '" & Forms!ViewQryResults!comboSelectSpecific & "'"
And to remove filter:
DoCmd.RunCommand acCmdRemoveAllFilters
I am attempting to create a sql statement in XE8 at runtime to search an oracle database based on the value in a textbox. I find multiple different ways that attempt to explain this online, but I am not understanding what it is asking.
I want to search a server based on a select statement and populate TDB components (labels only) based on the data. The furthest I have gotten is to get data populated, but the where
' ... somevalue = ' + textbox.text;
seems to have no effect.
What components do I need to make this happen? I am connected to the database, and it appears that I can get some kinda data out of it, but I can't seem to figure out how to filter the results. Obviously, I cannot create this sql statement at design time as the value of textbox.text will change depending on the user's input.
My error was in how to dynamically change what the data aware components got data as it would not always be the same. I had to manually go in and modify their datafield properties. Once I did this, my query functioned correctly.
So I have a form that I want the user to use to update multiple tables with. I do not want the form to be bound to the tables, as I would rather do this with VBA (I think, I don't know).
So here is a little table example
UserTable
UserID
First
Middle
Last
Division
Title
EquipTable
EquipID
AssignedLaptop
Model
Barcode
SoftTable
SoftID
SoftwareName
License#
Custom (running sum to calculate how many licenses are left....another question)
ExchangeTable
UserID
SoftID
EquipID
So that is how I set the tables up. All these text/cmb boxes exist on one table, and I would like to be able to save this data from this one form to all relative tables with a button click.
So can anyone help me with the following:
If I have this unbound form populate after a Create New button click, how then can I tell hidden text boxes (that ideally are to contain the " "ID numbers), to populate new ID numbers (auto-numbers), for each of the tables, in them, so that I can assign an UPDATE SQL statement to a SAVE button click, in the VB to save the data?
Could I set it up so that I just the "exchange table" (no idea why i named it that) populates the ID numbers for the other tables, instead of visa versa?
Am I going about this the wrong way
EDIT:
I was just trying to give you an example to see if what I was trying to do is possible with multiple tables (ultimately multiple Keys) on one form, and if so how does it differ from doing it with one form/table: I use the unbound approach alot because of the forms I have to build, and the need to constantly pas parameters from one form to the next in the VBA. I think it is faster to code it myself? So for this concept I always have a hidden text box on the form that usually has the IDnumber of the relative table. So to click save would just require a simple SQL = * WHERE Tbl_ID = frmID kinda idea.
All I was wondering were these questions?
When you run an INSERT, does the ID number need to be present in the STATEMENT or will access just assign the next relative one for you when you execute?
If not
Considering the method above, how can i determine this number (ID I need to use) myself, with code?
Another question? How do you defeat the mouse wheel scroll through records function on a bound form?
I see what you are saying, wording was strange on this but I do see where you are goign with this.
This is what you have:
You have an unbound form that is not linked to any table
This unbound form that is in no way linked to any table will be designed by you by adding some text boxes and also combo boxes and buttons
Within these textboxes you have some textboxes that are going to store the ID (The key value) of the row. So that when you do a save the ID number is set back to the text box
Once the ID number is set to this hidden field you can then issue updates to all tables that need this ID number
Does that sound right? If so it is very simple. All you have to do is once you click the "Create Button" perform the insert, something to this effect:
' Command to Insert Records.
Dim cmdInsert As New OleDbCommand()
cmdInsert.CommandText = "INSERT INTO AutoIncrementTest (Description) VALUES (?)"
cmdInsert.Connection = cnJetDB
cmdInsert.Parameters.Add(New OleDbParameter("Description", OleDbType.VarChar, 40, "Description"))
oleDa.InsertCommand = cmdInsert
Then you issue another command to grab the IDENTITY back, namely your ID:
' Create another command to get IDENTITY value.
cmdGetIdentity = New OleDbCommand()
cmdGetIdentity.CommandText = "SELECT ##IDENTITY"
cmdGetIdentity.Connection = cnJetDB
You can always get an identity with SELECT ##IDENTITY
So in your code behind you set the textbox to the value of SELECT ##IDENTITY.
I haven't done access in over 5 years but I remember doing something like this. Once you have this identity you place it in your hidden text box. This will help you perform your UPDATES that use this identity.
Here is a good place to start: http://support.microsoft.com/kb/815629
Here is another great article that may help you: http://support.microsoft.com/kb/815629