SQL update query linked to a control on a form - sql

In the query below, i would like to update the field named 'ID' in table tblDependencies03 with a value coming from the field 'ID' in table tblDependencies01. On my form I have a control named ID to allow me to identify which record in Table tblDependencies01 I would like to retrieve. Strangly however, this query works however creates a record (with the correct ID number in the ID column) but duplicates it for every record in the table tblDependencies01 regardless of what the ID number is. For example, if my control reflects record ID 96, and three records exist in table tblDependencies01 with ID 95,96 & 97, my end result in table tblDependencies03 will be 3 records created, all with ID '96'
Below is my code:
st_sql = "INSERT INTO tblDependencies03([ID])SELECT '" & ID & "' FROM tblDependencies01 WHERE [tbldependencies01].[ID] = ID "
Application.DoCmd.RunSQL (st_sql)

The condition in your SELECT is wrong.
Check your SELECT part of your query, and you will probably get more than one record. I also think that you don't really need any SELECT because you already have the value you are looking for. You can use VALUES:
st_sql = "INSERT INTO tblDependencies03 ([ID]) VALUES ('" & ID & "')"

Related

Autonumber - start from ZERO

So, I know how to add an autonumber field to a table using SQL:
dblocal.Data.Execute "CREATE TABLE " & TableName & " (" & FieldName & " COUNTER(1,1) )"
Where dblocal is the passed database reference with TableName & FieldName the appropriate names for the desired creation of the table.
However, I want the counter to start at ZERO not ONE. And I know it's possible because the table I need to repair / duplicate starts with ZERO
What am I not finding on the internet to aid me in this task?
My search-fu fails me.

Inserting into multiple tables at once based on a value you insert into one table first

I'm trying to create a row in multiple tables at once. The problem I'm running into is all the tables except the first table need the autonumber/primary key from the first INSERT statement. I'm not entirely sure what VALUE to enter in the tables beyond the first. Help is greatly appreciated!
Here is the code I'm using:
Private Sub cmdCreate_Click()
If DCount("*", "[tblRegSR]", "[WorkOrderID] = " & Me![txtID]) > 0 Then
MsgBox "This record already exists", vbOKOnly + vbExclamation, "Duplicate Record"
Else
DoCmd.RunSQL "INSERT INTO tblRegSR (WorkOrderID, CustomerID) VALUES (Me!txtID.Value, Me!Customer.Value)"
DoCmd.RunSQL "INSERT INTO tbFirstSR (ServiceRecordID) VALUES (WhatGoesHere)"
End If
End Sub
WhatGoesHere would typically be the ID field of the first table I inserted data into.
DoCmd.RunSQL "INSERT INTO tblRegSR (WorkOrderID, CustomerID) VALUES (Me!txtID.Value, Me!Customer.Value)"
Assuming you have a field called ID in tblRegSR as AutoNumber, you would insert it into the 2nd table like this:
DoCmd.RunSQL "Insert into tblFirstSR (ServiceRecordID) Select Max(ID) from tblRegSR "

Append data to linked table without knowing Primary Key of main table

I have a Staff Recruitment Database. When all formalities are complete I click a button and basic data is appended to the (recruited) Staff Database .
I also have data for the shift the recruit will work: Hours, Rate of pay etc. This goes into a Linked table.
To append this data I need to know the Primary Key of the recruit. How can I append the data automatically without looking at the table where the basic data is to find the PK?
I'm using INSERT INTO. Staff Database contains the main Staff table and the linked Shifts table.
If the "main" table has an AutoNumber field as its Primary Key then immediately after performing the INSERT INTO statement you can use some code like this to retrieve the PK value you just inserted:
Dim rst AS DAO.Recordset, newPK as Long
Set rst = CurrentDb.OpenRecordset("SELECT ##IDENTITY", dbOpenSnapshot)
newPK = rst(0).Value
rst.Close
Set rst = Nothing
You can then use the newPK value as a foreign key in the related tables.
Edit re: using the new value
Based on the code sample in your comment, try this instead:
strSQL = _
"INSERT INTO tblShifts (StartDt, [To], Hours, StaffLookup) " & _
"IN ""C:\__tmp\Staff.accdb"" " & _
"SELECT qryAdd.DateStarted, qryAdd.To, qryAdd.Hours, " & newPK & " AS StaffLookup FROM qryAdd"
If [tblShifts] really is a linked table then you shouldn't need to use the IN (mydatabase) clause because a linked table will behave just like a local table in this case. Note the corrections to the syntax as well, especially the bracketing of [To] which is a reserved word in Access.
Think I have got a solution. I can retrieve the PK into the recruitment db like this:
DoCmd.RunSQL "INSERT INTO tblCBSStaffLookup ( StaffLookupCBS, NINO ) " & _
"SELECT tblStaff.ID, tblStaff.NINO " & _
"FROM tblStaff IN 'C:\Users\Peter.Home-PC\Documents\NEMS\Databases\Frontends\Staff.accdb' " & _
"WHERE (((tblStaff.NINO)=[Forms]![frmSuccess]![NINO])) "
tblCBSStaffLookup is a table I have now made in the recruitment db to collect the PK and NINO.
WHERE matches the newly arrived NINO to a form in the recruitment db which already has the NINO. I have set up constraints to make sure that NINO's are valid. I have also set up a query in the recruitment db to retrive all NINO's from the main db, so that new recruits don't get added the the main db twice.

Copy a column from one table into another table

I have tried this with ALTER TABLE to create the column followed by INSERT INTO. This kind of works, except each subsequent column starts after the previous column has ended. I guess this is how insert into works, so is there a workaround or another query I can build?
I have been trying with updates but its not working out.
For reference, these were the alter/insert queries i used.
SQL = "ALTER TABLE [results] ADD COLUMN [" & fld.Name & "_result] TEXT(25)"
db.Execute SQL
SQL = "INSERT INTO [results] ([" & fld.Name & "_result]) SELECT [Result] As
[" & fld.Name & "_result] FROM [newtable]"
db.Execute SQL
Your insert statement assumes that the results table has only one column that you need to insert data into. This is unlikely to be true, if the table already had other columns before you executed the ADD COLUMN.
You will need to keep track of the columns in the results table, and provide data (or a default value) for each column.
It is rather unusual to expand a table's structure from inside an application. What are you trying to accomplish? Are you sure you can't accomplish it better by defining fixed tables and then adding data from your application?
UPDATE
Okay, I think I understand what you're describing. On the first iteration, the ALTER TABLE creates the first column. The INSERT adds a bunch of rows that have data in this first column.
On the second interation, the ALTER TABLE creates a second column. The INSERT creates a whole bunch of new rows, but only the second column is populated. The first column is all NULL because you didn't provide values for it. And so on and so forth for the third and subsequent iterations.
If your actual intention is to duplicate the source table and its data, then you should create your results table in a single pass. You know the column structure, right? Use a CREATE TABLE statement. Then write a single INSERT statement somewhat like the following:
INSERT INTO [results]
([field1_result], [field2_result], [field3_result])
SELECT [Result] As
[field1_result, [field2_result], [field3_result]]
FROM [newtable]
Is this what you have in mind?
Before you enter into the loop create your [results] table as
SQL = "CREATE TABLE [results] SELECT [primary_key] FROM [newtable]"
db.Execute SQL
Then at every iteration of the loop execute
SQL = "ALTER TABLE [results] ADD COLUMN [" & fld.Name & "_result] TEXT(25)"
db.Execute SQL
SQL = "UPDATE [results] SET r.[" & fld.Name & "_result] = n.[Result] " &
"FROM [results] r, [newtable] n " &
"WHERE r.[primary_key] = n.[primary_key]"
db.Execute SQL
So, if you had your [newtable] at its first two iterations like
[primary_key] [Results] [primary_key] [Results]
1 A 1 D
2 B 2 E
3 C 3 F
Your [results] table (after the above two iterations) would look like
[primary_key] [fld1_result] [fld2_result]
1 A D
2 B E
3 C F

How do I get rid of Duplicate Entries With Unique IDs in MS Access 2003?

I'm working on an MS Access Database with tons of duplicate entries. The problem is that there is a table of students, and sometimes instead of just updating a certain student's information, someone would just add the student in again with a different ID. I want to get rid of all the duplicates (which is a pain since there's barely any way to differentiate them), which would be fine by just deleting the duplicates, except that other tables may rely on the duplicate. How can I change all the tables that rely on a certain ID to rely on the ID that I choose to keep?
Here's what it looks like:
Student ID | L. Name |F. Name
ANDY-01 | Andy | Andy
ANDY-02 | Andy | Andy
Then in the courses table I'd have courses that ANDY-01 would have taken, and courses ANDY-02 would have taken. I want to merge all entries in all the tables that would have ANDY-01 and ANDY-02 as ANDY-01. How would I go about this?
(Don't worry about how I'm differentiating between ANDY-01 and ANDY-02)
+1 for Riho's answer. To update multiple tables you could create a procedure like the one below, and manually update the ID values and execute the procedure for each student.
If you have a table or query that maps the old and new IDs you could write another procedure to read the table and call this procedure for each student.
Public Sub UpdateStudent()
Dim oldID As String
Dim newID As String
oldID = "ID1"
newID = "ID2"
DoCmd.Execute "update another_table set student_id='" & newID & "' where student_id=" & oldID
DoCmd.Execute "update yet_another_table set student_id='" & newID & "' where student_id=" & oldID
End Sub
You just have to make some update SQL:
update another_table set student_id=:ID2 where student_id=:ID1