I've done this a zillion times, and I don't know what's changed.
Private Sub Foo()
dim rst as DAO.Recordset
set rst = CurrentDB.OpenRecordset("Select * From Table1;", dbOpenDynaset)
rst.movefirst
Do Until rst.EOF
DoCmd.RunSQL INSERT INTO Table2 (Last, First, Gender) VALUES (" & "' & rst!Last & '" & ", " & "' & rst!First & '" & ", " & "' & rst!Gender & '" & ");"
rst.MoveNext
Loop
End Sub
If I do this, the values inserted into Last, First and Gender are '" & rst!ColumnName & "' versus the actual data from the column.
If I omit the single quotes it works until it comes across a last name with a hypen or aposttrophe and then it throws a syntax error.
But I've done this same thing in code a zillion times the last 6 years and it's always worked and for whatever reason on this new project it's not proving the results I am used to.
Any ideas?
You seem to have that a bit mixed up:
DoCmd.RunSQL "INSERT INTO Table2 (Last, First, Gender) VALUES ('" & _
& rst!Last & "', '" & rst!First & "', '" & rst!Gender & "');"
Note that if you have names that contain apostrophes, the above will fail, so it is a good idea to escape them like so:
DoCmd.RunSQL "INSERT INTO Table2 (Last, First, Gender) VALUES ('" & _
& Replace(rst!Last,"'","''") & "', '" & Replace(rst!First,"'","''") _
& "', '" & rst!Gender & "');"
The other point that I wonder about is why are you doing this in steps? Why not:
strSQL = "INSERT INTO Table2 (Last, First, Gender) " _
& "SELECT Last, First, Gender FROM Table1 "
CurrentDB.Execute strSQL, dbFailOnError
Related
I am trying to create a Form that is used to manually enter data in certain scenarios. Most data is input from CSV files which is working fine. I have 4 tables, Part , Assembly , MachineOrder , and Job. I was able to write code for entering into the base table, Part, from the Form no problem. The issue now is entering data into the Assembly and MachineOrder tables where the Parts are being referenced by their PID autonumber field and the Assemblies are being referenced by their AID autonumbered field. I have tried many different kinds of methods to perform this of which you can see a bit of in my commented out code. What is there is what I believe to be my closest to correct code thus far with the error now being that Access asks me for the parameter value of rPID even though it is finding the value in the Dlookup function fine. I'm assuming the same is true for the rAID section as well.
Otherwise I'm getting errors of Key Violations when using the INSERT then UPDATE method you see commented out.
The form is called HOTEntry
Any advice on what my problem may be is greatly appreciated, I'm a student and this is my first time trying to use what I've learned in a professional application so any and all constructive criticism is wanted! Apologies if this is a rather specific question but I could really use the help on this since I've been working on it for two days to no avail...
My code:
Sub HOTParts2()
Dim rPID As Integer
Dim rAID As Integer
Dim dbs As DAO.Database
Dim sqlstr1 As String
Dim sqlstr2 As String
Dim sqlstr3 As String
Dim sqlstr4 As String
Set dbs = CurrentDb
'sqlstr1 = "INSERT INTO Assembly ( PID, ModelNum, ModelRev, ModelDescription ) " _
' & "SELECT (PID,Forms!HOTEntry!txtHotModel, Forms!HOTEntry!txtHotRev, Forms!HOTEntry!txtHotDes)" _
' & "FROM Part " _
' & "WHERE Part.PartName = Forms!HOTEntry!txtPartName AND Part.Config = Forms!HOTEntry!txtConfigEntry AND Part.Rev = Forms!HOTEntry!txtRevEntry"
sqlstr1 = "INSERT INTO Assembly ( ModelNum, ModelRev, ModelDescription,PID ) " _
& "VALUES (Forms!HOTEntry!txtHotModel, Forms!HOTEntry!txtHotRev, Forms!HOTEntry!txtHotDes," & "rPID" & ");"
'
'sqlstr2 = "UPDATE Assembly " _
' & "SET PID =" & rPID & " " _
' & "WHERE Assembly.ModelNum = Forms!HOTEntry!txtHotModel And Assembly.ModelDescription = Forms!HOTEntry!txtHotDes And Assembly.ModelRev = Forms!HOTEntry!txtHotRev;"
'
'sqlstr3 = "INSERT INTO MachineOrder ( AID, Serial, CustName ) " _
' & "SELECT (AID,Forms!HOTEntry!txtHotSerial, Forms!HOTEntry!txtHotCust)" _
' & "FROM Assembly" _
' & "WHERE Assembly.Model=Forms!HOTEntry!txtHotModel And ModelDescription= Forms!HOTEntry!txtHotDes And ModelRev = Forms!HOTEntry!txtHotRev; "
sqlstr3 = "INSERT INTO MachineOrder (Serial, CustName, AID ) " _
& "VALUES (Forms!HOTEntry!txtHotSerial, Forms!HOTEntry!txtHotCust," & "rAID" & ");"
'
'sqlstr4 = "UPDATE MachineOrder " _
' & "SET AID =" & rAID & " " _
' & "WHERE AID IS NULL;"
rPID = DLookup("PID", "Part", "PartName = " & "'" & Forms!HOTEntry!txtPartName & "'" & " And " & "Config = " & "'" & Forms!HOTEntry!txtConfigEntry & "'" & " And " & "Rev = " & "'" & Forms!HOTEntry!txtRevEntry & "'")
DoCmd.RunSQL sqlstr1
'DoCmd.RunSQL sqlstr2
rAID = DLookup("AID", "Assembly", "ModelNum = " & "'" & Forms!HOTEntry!txtHotModel & "'" & " And " & "ModelDescription = " & "'" & Forms!HOTEntry!txtHotDes & "'" & " And " & "ModelRev = " & "'" & Forms!HOTEntry!txtHotRev & "'")
DoCmd.RunSQL sqlstr3
'DoCmd.RunSQL sqlstr4
End Sub
Well, if you want to use the looked up rPID and rAID in a query, you need to do more than just set them in VBA. You can either manually fill them in in your SQL statement, use a parameter and a QueryDef and fill in the parameter in your QueryDef, or put the DLookUp inside your SQL statement.
Going with the first approach here, only unquoted rPID in your initial statement, and put it after rPID was set.:
rPID = DLookup("PID", "Part", "PartName = " & "'" & Forms!HOTEntry!txtPartName & "'" & " And " & "Config = " & "'" & Forms!HOTEntry!txtConfigEntry & "'" & " And " & "Rev = " & "'" & Forms!HOTEntry!txtRevEntry & "'")
sqlstr1 = "INSERT INTO Assembly ( ModelNum, ModelRev, ModelDescription,PID ) " _
& "VALUES (Forms!HOTEntry!txtHotModel, Forms!HOTEntry!txtHotRev, Forms!HOTEntry!txtHotDes," & rPID & ");"
DoCmd.RunSQL sqlstr1
I have a problem on how to insert data into two different table. So my requirements is this.
Under Group Details, The user need to click all the needed information on the dropdown menu and input on the textbox of the table grid view before clicking the ADD Link, after this the page will load displaying the Added Job Title and business group details. The user is allowed to input as many Job title as the user want.
I already finished the table but I have problems in saving the data that I input.
So my first table looks like this Before
and I edit it and this is my table Now
So my problem is this, in my database i have two table. One is EMPGROUP_TBL with columns SEQID, masterID, Business Unit, Division, Sub-Division etc. and the other is EMP_MASTERTBL with columns MasterID, Name, LastName, Jobtitle.
Now everytime I click Add link the jobtitle will not be able to save in the EMP_MASTERTBL so I create a code in VB.Net that will update the EMP_MASTERTBL table when I click the add button under Group Details.
Here's my codes.
If UpdateInsDelRecord("INSERT INTO EMPGROUP_TBL (MASTERID, BUSINESS_UNIT, " & _
"DIVISION, SUB_DIVISION, CLASSIFICATION, SUB_CLASSIFICATION) VALUES " & _
"('" & HandleQuote(Me.lblval_Empid.Text) & "', " & _
"'" & Me.ddl_BusinessUnit.SelectedValue.ToString() & "' ," & _
"'" & val_division & "' ," & _
"'" & val_subdivision & "' ," & _
"'" & Me.ddl_Classification.SelectedValue.ToString() & "' ," & _
"'" & Me.ddl_SubClassification.SelectedValue.ToString() & "')" & _
";" & _
"UPDATE EMP_MASTERTBL SET JOBTITLE = '" & Me.txtJobtitle.Text & "' " & _
"WHERE MASTERID = '" & Me.lblval_Empid.Text & "'") = True Then
Return True
Response.Redirect("eHR_EmpMaintenance.aspx")
Else
Return False
End If
But the user must be able to add as many as Jobtitle and EMPGROUP_TBL details as the user want. So I'm thinking that I'll just write another query for that? How can I add the Group Details and be able to add as many as Jobtitle as the user want?
CheckIfExist
I figured maybe I could use the CheckIfExist and if the employee has an existing data to the jobtitle, business unit, division, sub-division, classification and sub-classification similar to the one that you will add, the messagebox will show that the data already exist. If no data found then it will be able to add the details under the employee's group details. And if you input similar jobtitle but different business unit etc. the data will just be updated and vice versa.
Here's what my code for this.
Function SaveUserGroup() As Boolean
Try
Dim jobtitle As String = Me.txtJobtitle.Text
Dim businessunit As String = Me.ddl_BusinessUnit.SelectedValue
Dim division As String = Me.ddl_Division.SelectedValue
Dim subdivision As String = Me.ddl_SubDivision.SelectedValue
Dim classification As String = Me.ddl_Classification.SelectedValue
Dim subclassification As String = Me.ddl_SubClassification.SelectedValue
Dim CheckMasterTblIfExist As Boolean
Dim CheckGroupTblIfExist As Boolean
Dim insrtResult As Boolean
Dim seqid As String = Me.lblSEQID.Text
Dim emp_id As String = Request.QueryString("emp_id")
If jobtitle <> "" And businessunit <> "Please Select" And division <> "Please Select" And subdivision <> "Please Select" And classification <> "Please Select" And subclassification <> "Please Select" Then
CheckMasterTblIfExist = CheckRecord("SELECT MASTERID, JOBTITLE FROM EMP_MASTERTBL WHERE JOBTITLE = '" & jobtitle & "' AND MASTERID = '" & emp_id & "' ")
CheckGroupTblIfExist = CheckRecord("SELECT * FROM EMPGROUP_TBL WHERE BUSINESS_UNIT = '" & businessunit & "' AND DIVISION = '" & division & "' AND SUB_DIVISION = '" & subdivision & "' AND CLASSIFICATION = '" & classification & "' AND SUB_CLASSIFICATION = '" & subclassification & "' AND MASTERID = '" & emp_id & "' AND SEQID = '" & seqid & "'")
If Not CheckMasterTblIfExist And CheckGroupTblIfExist Then
insrtResult = UpdateInsDelRecord("UPDATE EMP_MASTERTBL SET JOBTITLE = '" & jobtitle & "' " & _
"WHERE MASTERID = '" + Me.lblval_Empid.Text + "'" & _
";" & _
"INSERT INTO EMPGROUP_TBL(MASTERID, BUSINESS_UNIT, " & _
"DIVISION, SUB_DIVISION, CLASSIFICATION, SUB_CLASSIFICATION) VALUES " & _
"('" & HandleQuote(Me.lblval_Empid.Text) & "', " & _
"'" & businessunit & "' ," & _
"'" & division & "' ," & _
"'" & subdivision & "' ," & _
"'" & classification & "' ," & _
"'" & subclassification & "')")
If Not insrtResult Then
MessageBox("alert('Error Ocurred While Inserting a Data.')")
Else
MessageBox("alert('Successfully Added.')")
End If
Else
MessageBox("alert('Data Already Exist.')")
End If
End If
Catch ex As Exception
MessageBox("Error Ocurred while Inserting a data")
Throw
End Try
End Function
I haven't been completed the code yet. I'm in the adding if there's no data and my problem is that the messagebox keeps on telling me that the data already exist even if there's still no employee's group details that added. Please help me with this.
begin tran
if exists (select * from table with (updlock,serializable) where key = #key)
begin
update table set ...
where key = #key
end
else
begin
insert into table (key, ...)
values (#key, ...)
end
commit tran
you can use like this
So all I'd like to do is add two queries into a table called tmpGroupSearch. I'm not sure how to do it wit out creating a record set and looping through every record and individually adding them in. I'm thinking there is a much easier way to do this I just can't find the proper structure.
Here are my queries:
"SELECT tblGroupHeader.GroupName" _
& ", tblGroupHeader.GroupNum" _
& ", tblAlsoKnown.AlsoKnown" _
& " FROM tblGroupHeader" _
& " LEFT JOIN tblAlsoKnown ON tblGroupHeader.GroupNum = tblAlsoKnown.GroupNum" _
& " WHERE tblGroupHeader.GroupName like '" & txtgroupSearch.Value & "*'" _
& " OR tblGroupHeader.GroupNum like '" & txtgroupSearch.Value & "*';"
"Select * FROM tblActionLog WHERE AlsoKnown LIKE '" & txtgroupSearch.Value & "*';"
You can follow an INSERT INTO clause with a list of values, like #Asad shows, or also a SELECT query. Do yourself a favor and always list the field names in your SQL or you are just creating time bombs for the future.
Dim strSelect1 As String
Dim strSelect2 As String
strSelect1 = "SELECT tblGroupHeader.GroupName" _
& ", tblGroupHeader.GroupNum" _
& ", tblAlsoKnown.AlsoKnown" _
& " FROM tblGroupHeader" _
& " LEFT JOIN tblAlsoKnown ON tblGroupHeader.GroupNum = tblAlsoKnown.GroupNum" _
& " WHERE tblGroupHeader.GroupName like '" & txtgroupSearch.Value & "*'" _
& " OR tblGroupHeader.GroupNum like '" & txtgroupSearch.Value & "*';"
strSelect2 = "Select * FROM tblActionLog WHERE AlsoKnown LIKE '" & txtgroupSearch.Value & "*';"
Dim strInsert1 As String
Dim strInsert2 As String
strInsert1 = "INSERT INTO tmpGroupSearch (GroupName, GroupNum, AlsoKnown) " & strSelect1
'the next version is valid SQL, but *dangerous* because field names are not enumerated
strInsert2 = "INSERT INTO tmpGroupSearch " & strSelect2
It is possible to write the INSERT INTO statement in two forms.
The first form does not specify the column names where the data will be inserted, only their values:
INSERT INTO table_name
VALUES (value1,value2,value3,...);
The second form specifies both the column names and the values to be inserted:
INSERT INTO table_name (column1,column2,column3,...)
VALUES (value1,value2,value3,...);
Test this parameter query in the Access query designer and adjust as needed so that it returns the row set you expect for the pSearchText parameter value you supply.
PARAMETERS pSearchText Text ( 255 );
SELECT gh.GroupName, gh.GroupNum, ak.AlsoKnown
FROM
tblGroupHeader AS gh
LEFT JOIN tblAlsoKnown AS ak
ON gh.GroupNum = ak.GroupNum
WHERE
gh.GroupName Like "'" & pSearchText & "*'"
OR gh.GroupNum Like "'" & pSearchText & "*'"
UNION ALL
SELECT al.GroupName, al.GroupNum, al.AlsoKnown
FROM tblActionLog AS al
WHERE al.AlsoKnown Like "'" & pSearchText & "*'"
Once you have it returning the correct data, convert it to an INSERT query by changing the beginning of the statement to this ...
PARAMETERS pSearchText Text ( 255 );
INSERT INTO tmpGroupSearch (GroupName, GroupNum, AlsoKnown)
SELECT gh.GroupName, gh.GroupNum, ak.AlsoKnown
... and the rest
Save that query as qryGroupSearchAppend. Then you can execute that query from your VBA code:
Dim qdf As DAO.QueryDef
Set qdf = CurrentDb.QueryDefs("qryGroupSearchAppend")
qdf.Parameters("pSearchText").Value = Me.txtgroupSearch.Value
qdf.Execute dbFailOnError
I have this code:
Set oConnection = Server.CreateObject("ADODB.Connection")
Set oRecordset = Server.CreateObject("ADODB.Recordset")
oConnection.Open "DRIVER={MySQL ODBC 5.1 Driver};SERVER=localhost;UID=xxxx;PWD=xxxx;DATABASE=xxxx; OPTION=3;"
Sqltemp = "INSERT INTO rsvptable (fname, lname, fbid, rsvp, streetaddress, city, state, zip, streetaddress2, cellphone, acode) " & _
"VALUES ('" & firstName & "', '" & lastName & "', " & fb & ", 0, '" & address1 & "', '" & city & "', '" & strState & "', " & zip & ", '" & address2 & "', " & cell & ", " & returnedNums & ")"
set newAdd = oConnection.execute(Sqltemp)
if newAdd.EOF then
response.write "end"
else
response.write "not end"
end if
And it keeps telling me this:
ADODB.Recordset error '800a0e78'
Operation is not allowed when the object is closed.
/add.asp, line 136
line 136 is this:
if newAdd.EOF then
What would i be overlooking here?
UPDATE
found my answer here! :o)
How to tell if a db update was successful?
two things:
you define oRecordset as the recordset, but then use & check eof on newAdd
Why are you trying to populate a recordet from an insert query?
http://www.w3schools.com/ado/met_conn_execute.asp
The results are stored in a new Recordset object if it is a
row-returning query. A closed Recordset object will be returned if it
is not a row-returning query.
INSERT is not a row-returning query, thus it returns a closed recordset, thus you can't .EOF it. Check the Rows Affected bu passing a variable as the second argument to Execute. If RowsAffected is 1, then you're set.
I have a DAO recordset that gets created fine and I can transfer the records from the set to a table, this is done row by row and works well but I am transfering a large amount of data at once so this can take a very long time row by row.
Is there a way to transfer the ENTIRE recordset in one go, rather than row by row
See below for current code in use -
Dim SendE1 As DAO.Recordset
Set SendE1 = CurrentDb.OpenRecordset("SELECT TBL_ImportTable.* FROM TBL_ImportTable", dbOpenDynaset)
SendE1.MoveLast
Do Until SendE1.EOF
sqlinsert = "INSERT INTO TBL_E1Jobs (StartDate, StartTime, EndDate, EndTime, Location, UserID, WorkStationID, DocumentNumber, E1Shift, OperSeq, Facility, AdjustedforShifts, WeekNum)" & _
" VALUES ('" & SendE1("StartDate") & "', '" & SendE1("StartTime") & "', '" & SendE1("EndDate") & "', '" & SendE1("EndTime") & "', '" & SendE1("Location") & "', '" & SendE1("UserID") & "', '" & SendE1("WorkstationID") & "', '" & SendE1("DocumentNumber") & "', '" & SendE1("E1Shift") & "', '" & SendE1("OperSeq") & "', '" & SendE1("Facility") & "', '" & SendE1("AdjustedforShifts") & "', '" & SendE1("WeekNum") & "') "
DoCmd.RunSQL (sqlinsert)
SendE1.MoveNext
Loop
SendE1.Close
Set SendE1 = Nothing
#cularis is correct. The right way to do this is in a SQL query. Having read your comments to his answer, there are a few steps you can take to avoid wiping out data that has not been copied:
Dim db As DAO.Database, RecCount As Long
'Get the total number of records in your import table to compare later
RecCount = DCount("*", "TBL_ImportTable")
'This line is IMPORTANT! each time you call CurrentDb a new db object is returned
' that would cause problems for us later
Set db = CurrentDb
'Add the records, being sure to use our db object, not CurrentDb
db.Execute "INSERT INTO TBL_E1Jobs (StartDate, StartTime, ..., WeekNum) " & _
"SELECT StartDate, StartTime, ..., WeekNum " & _
"FROM TBL_ImportTable", dbFailOnError
'db.RecordsAffected now contains the number of records that were inserted above
' since CurrentDb returns a new db object, CurrentDb.RecordsAffected always = 0
If RecCount = db.RecordsAffected Then
db.Execute "DELETE * FROM TBL_ImportTable", dbFailOnError
End If
Please note that if you run those queries on linked ODBC tables, you will need to include the dbSeeChanges option (ie, dbFailOnError + dbSeeChanges).
Not a DAO, but a SQL solution, that does what you need:
INSERT INTO TBL_E1Jobs (StartDate, StartTime, EndDate ...)
SELECT StartDate, StartTime, EndDate ... FROM TBL_ImportTable
INSERT INTO ... SELECT MSDN