Update function with case SQL and VBA - sql

I want to try to have a SQL function to update mine table and put a date in the column, I'm using a update function with a case, but I get the error that an operator is missing.
but I can't find the error, does anybody know where it is?
Public Function Add_date( _
ByVal startDate As String, _
ByVal strTableName As String, _
ByVal strFieldName As String, _
ByVal strNummeringField As String) _
As Boolean
Dim strSql As String
strSql = "ALTER TABLE " & strTableName & " ADD " & strFieldName & " date"
DoCmd.RunSQL strSql
strSql = "UPDATE " & strTableName & " SET " & strFieldName & " = CASE WHEN " & strNummeringField & " < 25 THEN '23-07-1991' ELSE '01-01-01' END"
MsgBox strSql
DoCmd.RunSQL strSql
End Function

Jet/ACE (the MS Access db engine) does not support CASE...WHEN. The equivalent for ternary operations is IIF (immediate if). Also, date delimiters are #, not '. Try this instead:
strSql = " UPDATE " & strTableName & _
" SET " & strFieldName & " = " & _
" IIf(" & strNummeringField & " < 25, #23-07-1991#, #01-01-01#)"
Also, you may run into trouble formatting your dates as DD-MM-YYYY, regardless of your regional settings. See International Dates in Access for more information.

One possibility is that the strings representing the table and column name contain invalid characters. Try enclosing them in square brackets:
strSql = "ALTER TABLE [" & strTableName & "] ADD [" & strFieldName & "] date"
DoCmd.RunSQL strSql
strSql = "UPDATE [" & strTableName & "] SET [" & strFieldName & "] = CASE WHEN [" & strNummeringField & "] < 25 THEN '23-07-1991' ELSE '01-01-01' END"

Related

How to Pass SQL Parameter to Form Using OpenArgs?

I have a Database (not built by me) that uses 3 separate forms to accomplish 1 thing.
I would instead like to pass a SQL string to the OpenArgs in order to utilize 1 form.
Original Code for form I'd like to utilize:
Private Sub Form_Open(Cancel As Integer)
Dim strSQL As String
If Not IsNull(Me.OpenArgs) Then
strSQL = "SELECT tbl_COMBINED.[First Name] AS [Name Badge], 'P' AS Logo, Format(Now(),""yyyy"") & STOCKHOLDERS MEETING' AS MEETING " _
& "FROM tbl_COMBINED " _
& "GROUP BY tbl_COMBINED.[First Name], 'P', Format(Now(),""yyyy"") & ' STOCKHOLDERS MEETING', " _
& "tbl_COMBINED.ACCOUNT, tbl_COMBINED.Came " _
& "HAVING tbl_COMBINED.ACCOUNT = '" & CStr(Me.OpenArgs) & "' " _
& "AND ((tbl_COMBINED.Came) Is Null Or (tbl_COMBINED.Came)) = 0"
Me.RecordSource = strSQL
End If
End Sub
Each of the other forms is called by using
DoCmd.OpenForm "frm_newmanualnamebadge", "", "",, acNormal
from the Main form and has the SQL string in the row source. I would like to eliminate the row source and utilize the 1 form. I set the string from each button to:
strManuel = "SELECT tbl_manual_name_badge.NAMEBADGE1, tbl_manual_name_badge.MEETING, " _
& "tbl_manual_name_badge.LOGO, tbl_manual_name_badge.Stockerholder " _
& "FROM tbl_manual_name_badge"
DoCmd.OpenForm "frm_newmanualnamebadge", "", "",, acNormal, strManual
Passing the strManual to the form as a SQL string, however, every time I run it I get a "#Name?" in the name field instead of the name entered.
Here is the code I used on the form:
If Not IsNull(Me.OpenArgs) Then
strSQL = "SELECT tbl_COMBINED.[First Name] AS [Name Badge], 'P' AS Logo " _
& "FROM tbl_COMBINED " _
& "GROUP BY tbl_COMBINED.[First Name], 'P', " _
& "tbl_COMBINED.ACCOUNT, tbl_COMBINED.Came " _
& "HAVING tbl_COMBINED.ACCOUNT = '" & CStr(Me.OpenArgs) & "' " _
& "AND ((tbl_COMBINED.Came) Is Null Or (tbl_COMBINED.Came)) = 0"
Me.RecordSource = strSQL
ElseIf IsNull(Me.OpenArgs) Then
strSQL = "SELECT tbl_manual_name_badge.NAMEBADGE1, tbl_manual_name_badge.MEETING, " _
& "tbl_manual_name_badge.LOGO, tbl_manual_name_badge.Stockerholder " _
& "FROM tbl_manual_name_badge"
Me.RecordSource = strSQL
End If
Well, you either pass one value, or you pass the whole sql string.
But, if you passing the WHOLE sql string for the form, then this makes no sense:
If Not IsNull(Me.OpenArgs) Then
strSQL = "SELECT tbl_COMBINED.[First Name] AS [Name Badge], 'P' AS Logo " _
& "FROM tbl_COMBINED " _
& "GROUP BY tbl_COMBINED.[First Name], 'P', " _
& "tbl_COMBINED.ACCOUNT, tbl_COMBINED.Came " _
& "HAVING tbl_COMBINED.ACCOUNT = '" & CStr(Me.OpenArgs) & "' " _
& "AND ((tbl_COMBINED.Came) Is Null Or (tbl_COMBINED.Came)) = 0"
Me.RecordSource = strSQL
I mean, OpenArgs is a WHOLE sel string, and I am VERY sure that ACCOUNT = " some huge sql string" will NEVER work.
So, you would want this:
Dim strSQL As String
If Not IsNull(Me.OpenArgs) Then
strSQL = me.OpenArgs
else
strSQL = "SELECT tbl_manual_name_badge.NAMEBADGE1, tbl_manual_name_badge.MEETING, " _
& "tbl_manual_name_badge.LOGO, tbl_manual_name_badge.Stockerholder " _
& "FROM tbl_manual_name_badge"
End If
Me.RecordSource = strSQL
So, our logic is now:
if passed sql string (openargs), then that becomes our sql
if no open arges, then use the defined sql we have in the on-load

SQL Statement Syntax - String vs. Parameter - MS Access - VBA

Select SQL Statement Grouping by CNTRY. I'm trying to replace CNTRY with a variable string - strtable. What I've done all morning, thus far, results in syntax errors.
If Left(lngstr1, 2) = 19 Then
strtable = "DTG" '<---this would replace CNTRY
Else
strtable = "US" '<---this would replace CNTRY
End If
strsql = "SELECT 'VCAP0112 - CNTRY' AS VCAP0112, [VCAP0112 - " & strtable & "].[RECV IND] AS OMU, [VCAP0112 - " & strtable & "].[LEGACY ACCT], " _
& "Sum([VCAP0112 - " & strtable & "].[1 to 30 Day]) AS [0 - 30], Sum([VCAP0112 - " & strtable & "].[RECV BALANCE]) AS TOTAL " _
& "FROM [VCAP0112 - " & strtable & "] INNER JOIN Urcrosswalk ON [VCAP0112 - " & strtable & "].[LEGACY ACCT] = Urcrosswalk.[Legacy GL]" _
& "Group BY 'VCAP0112 - CNTRY' , [VCAP0112 - " & strtable & "].[RECV IND], [VCAP0112 - " & strtable & "].[LEGACY ACCT] " _
& "HAVING ((([VCAP0112 - " & strtable & "].[RECV IND])='O' Or ([VCAP0112 - " & strtable & "].[RECV IND])='M' Or ([VCAP0112 - " & strtable & "].[RECV IND])='U'));"
As an attempt to resolve this myself, I've gotten to the following:
strsql = "SELECT 'VCAP0112 - '& " & strtable & " AS VCAP0112,...
But, upon execution, Access asks for parameters for either 'DTG' or 'US' String. When opening up the full Query in Design View, the String ('DTG' or 'US') is an unrecognized Variable. how do I resolve this?
Strtable serves as a placeholder for which either the string 'US' or 'DTG' is to be assigned depending on an IF THEN statement. As I had it originally 1., the string - strtable - will emerge as a variable needing a parameter in the SQL Statement.
To resolve this, single quotes encapsulating the double quotes that surround the variable will turn strtable into an actual placeholder for the string assigned to it 2.
1. Parameter: strsql = "SELECT 'VCAP0112 - '& " & strtable & " AS VCAP0112,
2. String: strsql = "SELECT 'VCAP0112 - '& '" & strtable & "' AS VCAP0112,
This...this is what I learned today.

How can I insert data from an Access form into a sql table using VBA?

Here is what I have, I'm trying to take fields from an Access form (data comes from one linked sql table) and insert them into another linked sql table:
StrSQL = "INSERT INTO [dbo_Expense_Projection] ([StatusID],[TravellerUFID],[Email]) " & _
VALUES(" & Me.StatusID & ", " Me.TravellerUFID & ", " Me.SubmitterUFID & ", " Me.email & ")
DoCmd.RunSQL StrSQL
But I am getting this error
Compile error: Sub or Function not defined
I think you are just missing some double quotes:
StrSQL = "INSERT INTO [dbo_Expense_Projection] ([StatusID],[TravellerUFID],[Email]) " & _
"VALUES(" & Me.StatusID & ", " Me.TravellerUFID & ", " Me.SubmitterUFID & ", """ & Me.email & """)"
DoCmd.RunSQL StrSQL
You can try to print the contents of StrSQL and check the query before running it:
Debug.Print StrSQL
but I prefer not to create SQL strings with concatenated values (what happens if Me.StravellerUFID contains a double quote?)
I would suggest you to insert data using DAO:
Dim rs as Recordset
Set rs = CurrentDb.OpenRecordset("dbo_Expense_Projection")
rs.AddNew
rs!StatusID = Me.StatusID
rs!TravellerUFID = Me.TravellerUFID
' ...other fields
rs.Update
rs.Close
There are also some ampersands missing in the SQL-String:
StrSQL = "INSERT INTO [dbo_Expense_Projection] ([StatusID],[TravellerUFID],[Email]) " & _
"VALUES(" & Me!StatusID & ", " & Me!TravellerUFID & ", " & Me!SubmitterUFID & ", """ & Me!email & """)"
And I think you should use exclamation mark between "Me" and fieldname. But I do not want to argue with the experts here about that... ;)
Here is what ended up working:
Dim StrSQL As String
StrSQL = "INSERT INTO dbo_Expense_Projection (StatusID,TravellerUFID,Email)
VALUES('" & Form!StatusID & "','" & Form!TravellerUFID & "','" & Form!Email & "')"
DoCmd.SetWarnings False
DoCmd.RunSQL StrSQL
DoCmd.SetWarnings True

Update another table when field is changed

I have a form contains "DateProduced" field. The table bound to it is called "Report".
I try to add after update event to this field and want this event to update "DateProduced" field in Quantity table if ID matches for both.
Me![Text0] displays the ID from Report field
Me![Text4] displays the DateProduced from Report field.
The event code is as below.
Private Sub Text4_AfterUpdate()
Dim strSQL As String
strSQL = "UPDATE Quantity " _
& "SET [DateProduced] = (#" & Me![Text4] & "#) " _
& "WHERE ID = (" & Me![Text0] & ")"
DoCmd.RunSQL strSQL
End Sub
But i can not succeed.
That date format will fail for values where dd/mm can be interchanged for a valid date. It should read:
Private Sub Text4_Exit(Cancel As Integer)
Dim strSQL As String
strSQL = "UPDATE Quantity " _
& "SET [DateProduced] = #" & Format(Me!Text4.Value, "yyyy\/mm\/dd") & "# " _
& "WHERE [ID] = " & Me![Text0].Value & ";"
DoCmd.RunSQL strSQL
End Sub
A note: You should change the names of Text0 etc. to meaningful names.
I made it work with the following code. Thx
Private Sub Text4_Exit(Cancel As Integer)
Dim strSQL As String
strSQL = "UPDATE Quantity " _
& "SET [DateProduced] = #" & Format(Me.Text4.Value, "dd-mm-yyyy") & "#" _
& "WHERE [ID] = (" & Me![Text0] & ");"
DoCmd.RunSQL strSQL
End Sub

Error SQL in VBA Access 2010

I'm trying to write a query in MS Access 2010 in order to use it to print a report, but it gives me "missing parameter" error in "set qd" line, hereunder is the code i wrote, can you please help me and tell me what is wrong with my code:
`Private Sub Command5_Click()
Dim qd As DAO.QueryDef
Dim rs As DAO.Recordset
Dim strSql As String
Dim strFrom, strTo As String
strFrom = [Forms]![FrmPrintSelection]![txtFrom]
strTo = [Forms]![FrmPrintSelection]![txtTo]
strSql = "SELECT tblInvoiceHead.CustomerNumber,
tblCustomers.AccountName,tblCustomers.Address,
tblCustomers.Phone1, tblCustomers.Phone2," _
& "tblCustomers.Mobile1, tblCustomers.Mobile2, tblInvoiceHead.InvoiceNumber,
tblInvoiceHead.InvoiceDate, tblInvoiceHead.TotalInvoice," _
& "tblInvoiceHead.CashDiscount, TblInvoiceDetails.Item, TblInvoiceDetails.Unit,
TblInvoiceDetails.Qtn, TblInvoiceDetails.Price," _
& "TblInvoiceDetails.[Discount%], TblInvoiceDetails.CashDiscount,
TblInvoiceDetails.NetUnitPrice, TblInvoiceDetails.TotalPrice, tblInvoiceHead.InvoiceType" _
& "FROM (tblCustomers INNER JOIN tblInvoiceHead ON tblCustomers.AccountNumber =
tblInvoiceHead.CustomerNumber) INNER JOIN TblInvoiceDetails" _
& "ON tblInvoiceHead.InvoiceNumber = TblInvoiceDetails.InvoiceNumber" _
& "WHERE (((tblInvoiceHead.InvoiceNumber) Between " & strFrom & " And " & strTo & "))"
Set qd = CurrentDb.CreateQueryDef("RepInv", strSql)
Set rs = qd.OpenRecordset
'DoCmd.OpenQuery "repinv", strSql
Reports!repinvoicetest.RecordSource = "repinv"
DoCmd.OpenReport "repinvoicetest", acViewPreview
End Sub
`
Usually the error "missing parameter" means that you spelled one of your columns wrong. If you take your sql and paste it into a new query (temp, don't save) and run it, the misspelled column will pop up a window asking you to provide a value for that "parameter" (because MSAccess is assuming that you never would misspell a column name).
In your query above, you might have copy/pasted it wrong, but if not, then you don't have enough spaces between your words as you continue them on the next line. For instance, your SQL string would end up having some stuff in it like "InvoiceTypeFROM", because you didn't have an extra (necessary) space in there.
Try this query instead:
strSql = "SELECT tblInvoiceHead.CustomerNumber, " _
& " tblCustomers.AccountName,tblCustomers.Address, " _
& " tblCustomers.Phone1, tblCustomers.Phone2, " _
& " tblCustomers.Mobile1, tblCustomers.Mobile2, tblInvoiceHead.InvoiceNumber, " _
& " tblInvoiceHead.InvoiceDate, tblInvoiceHead.TotalInvoice, " _
& " tblInvoiceHead.CashDiscount, TblInvoiceDetails.Item, TblInvoiceDetails.Unit, " _
& " TblInvoiceDetails.Qtn, TblInvoiceDetails.Price, " _
& " TblInvoiceDetails.[Discount%], TblInvoiceDetails.CashDiscount, " _
& " TblInvoiceDetails.NetUnitPrice, TblInvoiceDetails.TotalPrice, " _
& " tblInvoiceHead.InvoiceType " _
& " FROM (tblCustomers INNER JOIN tblInvoiceHead " _
& " ON tblCustomers.AccountNumber = tblInvoiceHead.CustomerNumber) " _
& " INNER JOIN TblInvoiceDetails " _
& " ON tblInvoiceHead.InvoiceNumber = TblInvoiceDetails.InvoiceNumber " _
& " WHERE (((tblInvoiceHead.InvoiceNumber) Between " & strFrom & " And " & strTo & "))"
Notice how I added a lot of unncessary spaces at the begining and end of each line. All of those extra spaces will be ignored. However, if there are too few, then you will get errors. It is a simple trick that I stick-with.