I have a sub form with staff records on it within a main form. I am trying to allow the user to select a record from the sub form and add it to a table, here is my code which, to me, looks correct. However it gives me an error saying "Syntax error in INSERT INTO"
Private Sub Command3_Click()
Dim dbs As Database
Dim sqlstr As String
Set dbs = CurrentDb
Forename = Nz(Forms!frm_Capex_Submission!frm_staffSub.Form.shy_forename, "")
Surname = Nz(Forms!frm_Capex_Submission!frm_staffSub.Form.shy_surname, "")
emp_no = Nz(Forms!frm_Capex_Submission!frm_staffSub.Form.shy_empno, "")
CAP_ID = Forms!frm_Capex_Submission!CAP_ID
sqlstr = "INSERT INTO tbl_CapexStaff ( Forename, Surname, EmployeeID, CAP_ID) )" _
& " SELECT '" & Nz(Me!shy_forename, "") & "' AS Expr1, '" & Nz(Me!shy_surname, "") & "' AS Expr2, '" & Nz(Me!shy_empno, "") & " AS Expr3, " & Forms!frm_Capex_Submission.CAP_ID & " as expr4, """
dbs.Execute (sqlstr)
tbl_CapexStaff.Requery
End Sub
There is an extra ")" in your query
INSERT INTO tbl_CapexStaff ( Forename, Surname, EmployeeID, CAP_ID) )
Related
`Option Compare Database
Option Explicit
Dim argcount As Integer
Dim mysql As String, msg As String, mysource As String, mycriteria As String, mysource1 As String, mysql1 As String
Private Sub AddtoWhere(FieldValue As Variant, FieldName As String, mycriteria As String, argcount As Integer)
' Create criteria for WHERE clause.
If FieldValue <> "" Then
' Add "and" if other criterion exists.
If argcount > 0 Then
mycriteria = mycriteria & " and "
End If
' Append criterion to existing criteria.
' Enclose FieldValue and asterisk in quotation marks.
mycriteria = (mycriteria & FieldName & " Like " & Chr(34) & FieldValue & Chr(42) & Chr(34))
' Increase argument count.
argcount = argcount + 1
End If
End Sub
Private Sub Search_Click()
Dim Search As String
here:
argcount = 0
' Initialize SELECT statement.
mysql = "SELECT * FROM tbltab WHERE "
mycriteria = ""
mysql1 = "SELECT * FROM tblTemp WHERE "
mycriteria = ""
' Use values entered in text boxes in form header to create criteria for WHERE clause.
AddtoWhere cboProduct, "ABC1", mycriteria, argcount
AddtoWhere cboSource, "ABC2", mycriteria, argcount
AddtoWhere cboPType, "ABC3", mycriteria, argcount
'If no criterion specifed, stop the search.
'you'll be glad you did if there are thousands of Persons maybe.
If mycriteria = "" Then
mycriteria = True
End If
' Create SELECT statement.
mysource = mysql & mycriteria
mysource1 = mysql1 & mycriteria
Dim strval As String
'set the recordsource of the subform to the resultset
Me!sfrmCap.Form.RecordSource = mysource
Me!sfrmCapTemp.Form.RecordSource = mysource1
Exit_cmdsearch_Click:
Exit Sub
Err_cmdsearch_Click:
DoCmd.Hourglass False
DoCmd.Echo True
MsgBox Err.Description & " Person Search Command Cancelled", vbInformation, "Person Search Command Cancelled"
Resume Exit_cmdsearch_Click
End Sub
`I have a form in which there are 2 subform. I have a search button which when click search record using combo box values but in one combo box it display just related record not the complete search.
Can anyone help me in this.
Thank you.
In AddtoWhere() you assemble your WHERE clause, adding new conditions like this:
mycriteria = (mycriteria & FieldName & " Like " & Chr(34) & FieldValue & Chr(42) & Chr(34))
If you are unsure about what this actually does, you can put a breakpoint on the line (double clicking in the margin in front of the line) and see for yourself while executing the program.
If you do, you'll find out that a new condition like this will be added:
Source Like "Pre 2017 Source1*"
The * (encoded with Chr(42) in your code) acts as a joker matching any characters, so this condition returns everything that begins with Pre 2017 Source1 - as you can see in the search results.
If you do not want this behaviour, just remove the star from the SQL code and only exact matches will be returned.
Btw.: You should improve that code line like this:
mycriteria = mycriteria & FieldName & " LIKE '" & Replace(FieldValue, "'", "''") & "'"
This removes the unnecessary use of Chr(), replaces double quotes by single quotes as SQL string delimiters as it is recommended, and enables the code to handle values that contain quotes, which would otherwise result in a runtime error.
Here is my table structure:
ID1 - autonumber
TDate - Date/Time
TTime - Date/Time
TID - Text
TMessage - Text
Tcode - text
TMessage value can be 100+ characters. There can be more than 1 TMessage for each TID
Sample input:
TDate TID TTime TMessage
1/9/2014 93378 12:28:28 PM aaaaaaaaaaaa
7/24/2014 02645 12:56:22 PM bbbbbbbbbbbb
7/24/2014 02645 12:56:30 PM cccccccccccc
Output should be:
TDate, TID, TMessage
1/9/2014 93378 aaaaaaaaaa
7/24/2014 02645 bbbbbbbbbb,cccccccccccc (the output can be more than 255 chars.)
This is my query/module (got from Stackoverflow and Allen Brown)
Query (SQL View)
SELECT sub.TDate, sub.TID, ConcatRelated("[TMessage]","RawData2","[TDate] = '" & sub.TDate & "' AND [TID] = '" & sub.TID & "'","[TDate], [TID]") AS concat_Message
FROM (SELECT q.TDate, q.TID FROM RawData2 AS q GROUP BY q.TDate, q.TID) AS sub
ORDER BY sub.TDate, sub.TID;
Function :
Option Compare Database
Public Function ConcatRelated(strField As String, _
strTable As String, _
Optional strWhere1 As Date, _
Optional strWhere2 As String, _
Optional strOrderBy1 As Date, _
Optional strOrderBy2 As String, _
Optional strSeparator = ", ") As Variant
On Error GoTo Err_Handler
'Purpose: Generate a concatenated string of related records.
'Return: String variant, or Null if no matches.
'Arguments: strField = name of field to get results from and concatenate.
' strTable = name of a table or query.
' strWhere = WHERE clause to choose the right values.
' strOrderBy = ORDER BY clause, for sorting the values.
' strSeparator = characters to use between the concatenated values.
'Notes: 1. Use square brackets around field/table names with spaces or odd characters.
' 2. strField can be a Multi-valued field (A2007 and later), but strOrderBy cannot.
' 3. Nulls are omitted, zero-length strings (ZLSs) are returned as ZLSs.
' 4. Returning more than 255 characters to a recordset triggers this Access bug:
' http://allenbrowne.com/bug-16.html
Dim rs As DAO.Recordset 'Related records
Dim rsMV As DAO.Recordset 'Multi-valued field recordset
Dim strSql As String 'SQL statement
Dim strOut As String 'Output string to concatenate to.
Dim lngLen As Long 'Length of string.
Dim bIsMultiValue As Boolean 'Flag if strField is a multi-valued field.
'Initialize to Null
ConcatRelated = Null
'Build SQL string, and get the records.
strSql = "SELECT " & strField & " FROM " & strTable
If strWhere1 <> vbNullString And strWhere2 <> vbNullString Then
strSql = strSql & " WHERE " & strWhere1 And strWhere2
End If
If strOrderBy1 <> vbNullString And strOrderBy2 <> vbNullString Then
strSql = strSql & " ORDER BY " & strOrderBy1 And strOrderBy2
End If
Set rs = DBEngine(0)(0).OpenRecordset(strSql, dbOpenDynaset)
'Determine if the requested field is multi-valued (Type is above 100.)
bIsMultiValue = (rs(0).Type > 100)
'Loop through the matching records
Do While Not rs.EOF
If bIsMultiValue Then
'For multi-valued field, loop through the values
Set rsMV = rs(0).Value
Do While Not rsMV.EOF
If Not IsNull(rsMV(0)) Then
strOut = strOut & rsMV(0) & strSeparator
End If
rsMV.MoveNext
Loop
Set rsMV = Nothing
ElseIf Not IsNull(rs(0)) Then
strOut = strOut & rs(0) & strSeparator
End If
rs.MoveNext
Loop
rs.Close
'Return the string without the trailing separator.
lngLen = Len(strOut) - Len(strSeparator)
If lngLen > 0 Then
ConcatRelated = Left(strOut, lngLen)
End If
Exit_Handler:
'Clean up
Set rsMV = Nothing
Set rs = Nothing
Exit Function
Err_Handler:
MsgBox "Error " & Err.Number & ": " & Err.Description, vbExclamation, "ConcatRelated()"
Resume Exit_Handler
End Function
Currently, this is the output:
TDate TID Concat_Message
1/9/2014 93378 #Error
7/24/2014 02645 #Error
7/24/2014 04533 #Error
Question 1 - What could be the reason for the Error? How to solve it?
Question 2 - Can I just create a table manually with Memo field so I can store the result of the Query to this table?
I have done that before, but in this case I have an insert into table query where value of the column of the target table comes as a result from another query. Having that, I'm not sure if my parametarized query is formatted the right way.
Here is an original query without before Sql Injection fix:
cmd.CommandText += "insert into controlnumber (controlnumber, errorid)
values ('" + ControlNumber + "', (select errorid from error where
errordescription = '" + ErrorDescription + "' and errortype = '" +
ErrorType + "' + and applicationid = " + ApplicationID + " and statusid =
" + StatusID + " and userid = " + UserID + " and errortime = '" +
ErrorTime + "');";
This is the query after I tried to fix Sql Injection:
cmd.CommandText = "insert into ControlTable(ControlNumber, ErrorID)
values (#ControlNum, (select errorid from error where errordescription =
#ErrorDescription and errortype = #errorType and applicationid =
#ApplicationID and statusid = #StatusID and userid = #UserID and
errortime = #ErrorTime)"
This is where I add parameters:
.....
command.CommandType = CommandType.Text
command.Parameters.AddWithValue("#ErrorDescription ", ErrorDesc);
command.Parameters.AddWithValue("#ControlNum", cntNumber);
command.Parameters.AddWithValue("#errorType",ErrorType);
command.Parameters.AddWithValue("#ApplicationID",AppID);
command.Parameters.AddWithValue("#StatusID",StatusID);
command.Parameters.AddWithValue("#UserID",UserID);
....
I'm just wondering if my CommandText is formatted the right way.
Thank's
try this:
cmd.CommandText = "insert into ControlTable(ControlNumber, ErrorID)
select #ControlNum, errorid from error where errordescription =
#ErrorDescription and errortype = #errorType and applicationid =
#ApplicationID and statusid = #StatusID and userid = #UserID and
errortime = #ErrorTime)"
When using INSERT INTO SELECT FROM, you do not use keyword VALUES. The syntax is:
INSERT INTO TABLE(columns) SELECT ... FROM TABLE2
I am trying to update a date field in a table to the current date when a button is clicked on a form and that given field is empty. However, when the field is updated, the output is the time 12:00:05, not a date at all. When year(date) is used instead, 7/7/1905 is the output. I am not sure why these values are my outputs. Here is my code:
Dim ctl As Control
Set ctl = [Forms]![frm1]![subfrm1].[Form]![CloseDate]
If IsNull(ctl) Then
DoCmd.SetWarnings False
DoCmd.RunSQL "Update tbl1 SET [CloseItem] = ""YES"" WHERE [ID] = " & [Forms]![frm1]![ID].Value & " AND [Item#] = " & [Forms]![frm1]![subfrm1].[Form]![ItemID].Value
DoCmd.RunSQL "Update tbl1 SET [CloseDate] = " & Date & " WHERE [ID] = " & [Forms]![frm1]![ID].Value & " AND [ItemID] = " & [Forms]![frm1]![subfrm1].[Form]![ItemID].Value
' Output is 12:00:05
' OR DoCmd.RunSQL "Update tbl1 SET [CloseDate] = " & Year(Date) & " WHERE [ID] = " & [Forms]![frm1]![ID].Value & " AND [ItemID] = " & [Forms]![frm1]![subfrm1].[Form]![ItemID].Value
DoCmd.RefreshRecord
' Output is 7/7/1905
End If
How can I get it to output the correct date?
Examine the string your code builds for this segment of the UPDATE statement. (This is an example copied from the Access Immediate window. You can go there with Ctrl+g)
? "Update tbl1 SET [CloseDate] = " & Date & " WHERE [ID] = "
Update tbl1 SET [CloseDate] = 2/16/2015 WHERE [ID] =
The db engine does not see 2/16/2015 as a Date/Time value. Instead, it treats that as 2 divided by 16 divided by 2015. And the resulting number, when expressed as a Date/Time value, gives you this ...
? Format(2/16/2015, "yyyy-m-d hh:nn:ss")
1899-12-30 00:00:05
You can signal the db engine that 2/16/2015 is a Date/Time value by enclosing it in # delimiters like this: #2/16/2015#
However, since the db engine understands the Date() function, you can use that function name directly in your UPDATE statement and not bother about concatenating in a value with proper delimiters.
Dim strUpdate As String
strUpdate = "Update tbl1 SET [CloseDate] = Date() WHERE [ID] = " & _
[Forms]![frm1]![ID].Value & " AND [ItemID] = " & _
[Forms]![frm1]![subfrm1].[Form]![ItemID].Value
Debug.Print strUpdate
CurrentDb.Execute strUpdate, dbFailOnError
Can anyone point me to an example of an Access form which can create multiple records (in a single table) based on one form?
To expand: we're recording information about time spent on a project on a given date. We've had a request for a single form that would allow a user to enter data for 5 (or 7) days of a given week on a single form. He/she would pick a week from a calendar control, a project from a listbox, then enter up to 7 numbers for the hours spent that week.
I did check questions 5294128, which doesn't seem applicable, and question 8070706, which seems to imply that this can only be done in VBA (not using the GUI). Any alternatives?
Thanks.
Something on these lines should suit. This is an unbound form with a subform.
You can get the form type from the form wizard
To work properly, you will need a little code, say:
Private Sub cmdGo_Click()
Dim rs As DAO.Recordset
Dim sSQL As String
Dim sSDate As String
Dim sEDate As String
sSDate = "#" & Format(Me.txtStartDate, "yyyy/mm/dd") & "#"
sEDate = "#" & Format(Me.txtStartDate + Me.txtNoDays, "yyyy/mm/dd") & "#"
sSQL = "SELECT * FROM MyTable WHERE DataDate Between " & sSDate _
& " AND " & sEDate
Set rs = CurrentDb.OpenRecordset(sSQL)
If rs.RecordCount < Me.txtNoDays Then
AddRecords sSDate, sEDate
End If
Me.DataSubform.Form.RecordSource = sSQL
End Sub
Sub AddRecords(sSDate, sEDate)
''Uses counter table with integers from 0 to
''highest required number
''Another useful table is a calendat table, which would
''save some work here.
sSQL = "INSERT INTO MyTable (DataDate) " _
& "SELECT AddDate FROM " _
& "(SELECT " & sSDate _
& " + [counter.ID] AS AddDate " _
& "FROM [Counter] " _
& "WHERE " & sSDate _
& "+ [counter.ID] Between " & sSDate _
& " And " & sEDate & ") a " _
& "WHERE AddDate NOT In (SELECT DataDate FROM MyTable)"
CurrentDb.Execute sSQL, dbFailOnError
End Sub