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

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.

Related

Is it the same to insert into tables from query as from table using VBA?

so this is my code below it works just fine when selecting from a table :
Private Sub cmdStart_Click()
Dim strSql1 As String
Dim strSql2 As String
Dim strSql3 As String
Dim strSql4 As String
Dim qdef As DAO.QueryDef
Dim dbs As DAO.Database
Dim rs As DAO.Recordset
Set dbs = CurrentDb
strSql1 = "insert into qoyod_details (qaed_num,f_year,qaed_date,l_value,Hesab_code) " & _
"select " & Forms("qoyod").qaed_num & " , " & Forms("qoyod").f_year & " , format('" & Forms("qoyod").qaed_date & "' , 'dd/mm/yyyy') , sum(sale_bill_total), 167 " & _
"from sale_bill where sale_bill_date between format( '" & Me.cmbQFrom & "' ,'mm/dd/yyyy') and format( '" & Me.cmbQTo & "' ,'mm/dd/yyyy') and sale_bill_type = 1 "
dbs.Execute strSql1
but when I try to select from a query it just wont work
is there something am doing wrong ?
Thanks in advance.
First you'll need to enclose your data correctly:
numbers need no enclosure: 200
string need to be enclosed with ' or ": 'String' or "String"
Dates need to be enclosed with #: #2020-11-22#
When concatenating strings to an SQL string I usually use the single quotes '
So just guessing on what the field data types are, here is what you SQL string should look like:
strSql1 = "insert into qoyod_details (qaed_num,f_year,qaed_date,l_value,Hesab_code) " & _
"select " & Forms("qoyod").qaed_num & " , " & Forms("qoyod").f_year & " , #" & format(Forms("qoyod").qaed_date, "yyyy-mm-dd") & "#, sum(sale_bill_total) , 167 " & _
"from sale_bill where sale_bill_date between #" & format( Me.cmbQFrom, "yyyy-mm-dd") & "# and #" & format(Me.cmbQTo, "yyyy-mm-dd") & "# and sale_bill_type = 1"
dbs.Execute strSql1
To simplify date conversion use the ISO format yyyy-mm-dd, this will prevent any accidental switching between the day and month in certain configurations.
If you're still getting an error, then try printing the result to the Immediate Window like this for troubleshooting:
Debug.Print strSql1
dbs.Execute strSql1
before trying to execute the string.

Run-time error ‘3061’: Too few parameters expected 1

i had this error when i was trying to INSERT records to a local table with VBA.
I have checked the data type and putting in the quotes for the the short text data type but it doesn't work.
table_newid = "SELECT Cint(t1." & id_name(i) & "_new), " & Replace(select_column_str, local_table_name, "t2") & " FROM " & vbCrLf & _
"(SELECT CInt(DCount(""[" & id_name(i) & "]"", """ & qry_distinct_id_name & """, ""[" & id_name(i) & "]<="" & [" & id_name(i) & "])) as " & id_name(i) & "_new, * FROM " & qry_distinct_id_name & ") AS t1 " & vbCrLf & _
"LEFT JOIN " & local_table_name & "_ALL as t2 " & vbCrLf & _
"ON t1." & id_name(i) & " = t2." & id_name(i) & " " & vbCrLf & _
"WHERE t2.database = '" & database_name & "'"
strQuery = "INSERT INTO " & local_table_name & "_temp (" & temp_field(i) & ", " & Replace(select_column_str, local_table_name & ".", "") & ") " & vbCrLf & table_newid
Debug.Print strQuery
DoCmd.SetWarnings False
db.Execute strQuery
DoCmd.SetWarnings True
From the debug.print, i have got:
INSERT INTO TblLUMachineTypes_temp (MachTypeID_new, MachTypeID, MachTypeCode, MachTypeMod, MachTypeDesc, MachTypeDisc, NewCode, Approved, mttime, CreatedBy, CreatedTS, ModifiedBy, ModifiedTS)
SELECT t1.MachTypeID_new, t2.MachTypeID, t2.MachTypeCode, t2.MachTypeMod, t2.MachTypeDesc, t2.MachTypeDisc, t2.NewCode, t2.Approved, t2.mttime, t2.CreatedBy, t2.CreatedTS, t2.ModifiedBy, t2.ModifiedTS FROM
(SELECT CInt(DCount("[MachTypeID]", "qry_TblLUMachineTypes_id_distinct", "[MachTypeID]<=" & [MachTypeID])) as MachTypeID_new, * FROM qry_TblLUMachineTypes_id_distinct) AS t1
LEFT JOIN TblLUMachineTypes_ALL as t2
ON t1.MachTypeID = t2.MachTypeID
WHERE t2.database = 'CPM-252-2'
When i copied this query and execute it manually, it works fine but not with VBA. Any idea?
Thanks in advance.
Remove all the & vbCrLf from your code, they are not necessary and I assume they corrupt the SQL syntax.
I found the problem. I found that qry_distinct_id_name query table has a Dlookup function in there that returns a string value, which will work when executing the query manual but doesn't work when you run it with VBA. So I have re-written the code to put in the quote before and after dlookup() function.

SQL getting name from userform

I am having a little trouble with my SQL in access
CurrentDb.Execute "INSERT INTO _tbl_Structure " & _
"SELECT * " & _
"FROM [MS Access;pwd=" & strPassword & ";database=" & DBpath & "\" & DBname & "].[" & tblStructure & "] " & _
"WHERE [user] = '" & [Forms!frm_Advisors_Stats-manager].[Position]
The issue appears to be with
[Forms!frm_Advisors_Stats-manager].[Position]
Any help on what I am doing wrong here?
The position textbox shows if the person logged in is a manager or not. If they are a manager as stated on the userform is pulls all records the manager has on the team
The error shown is:
External name not defined
Or use correct bracketing:
[Forms]![frm_Advisors_Stats-manager]![Position]
Since you're using string concatenation, your object notation needs to be valid for VBA. Since your object name contains a hyphen, you need to properly refer to it using the forms collection and without the bang operator.
"WHERE [user] = '" & Forms("frm_Advisors_Stats-manager").Position.Value & "'"
Another way to reference a control on a form that I used a lot is:
Form_Advisors_Stats-manager.Position
Therefore:
CurrentDb.Execute "INSERT INTO _tbl_Structure " & _
"SELECT * " & _
"FROM [MS Access;pwd=" & strPassword & ";database=" & DBpath & "\" & DBname & "].[" & tblStructure & "] " & _
"WHERE [user] = '" & Form_Advisors_Stats-manager.Position & "'"

Using NZ in a function in VBA to build query

I am really struggling here. I am building up a query inside VBA to link to several tables inside Oracle and inside Access. I need to make sure what I have uploaded to Oracle Matches what is in the Access DB.
I have:
SourceField1 (Always populated)
SourceField2 (Sometimes populated)
If source field 2 is blank I want to ignore it and not join to it. The best way I have done this is try with an Nz and replace with SourceField1.
strSQL = "INSERT INTO ERROR_TABLE (ORACLE_FIELD, TRANSFORM_FIELD) SELECT " & MatchValues!ORACLE_TABLE_NAME & "." & MatchValues!FieldName & ", " & MatchValues!TRANSFORM_TABLE_NAME & "." & MatchValues!FieldName
strSQL = strSQL & " FROM " & MatchValues!TRANSFORM_TABLE_NAME & " INNER JOIN " & MatchValues!xfTableName
strSQL = strSQL & " ON " & MatchValues!TRANSFORM_TABLE_NAME & "." & MatchValues!SourceField1 & " = " & MatchValues!xfTableName & "." & MatchValues!ReferenceField1 & ""
strSQL = strSQL & " AND " & MatchValues!TRANSFORM_TABLE_NAME & ".Nz(" & MatchValues!SourceField2 & "," & MatchValues!SourceField1 & ") = " & MatchValues!xfTableName & ".Nz(" & MatchValues!ReferenceField2 & "," & MatchValues!ReferenceField1 & ")"
strSQL = strSQL & " INNER JOIN " & MatchValues!ORACLE_TABLE_NAME & " ON (" & MatchValues!xfTableName
strSQL = strSQL & ".KEYVAL = " & MatchValues!ORACLE_TABLE_NAME & ".KEYVAL)"
strSQL = strSQL & " WHERE (" & MatchValues!TRANSFORM_TABLE_NAME & "." & MatchValues!FieldName
strSQL = strSQL & " <> " & MatchValues!ORACLE_TABLE_NAME & "." & MatchValues!FieldName & ")"
Which gives me this:
INSERT INTO ERROR_TABLE (ORACLE_FIELD, TRANSFORM_FIELD) SELECT UNI73MART1_DCappl.DECSN, tbluniDCappl.DECSN FROM tbluniDCappl INNER JOIN XF_DC_ref ON tbluniDCappl.REFVAL = XF_DC_ref.REFVAL AND tbluniDCappl.Nz(,REFVAL) = XF_DC_ref.Nz(,REFVAL) INNER JOIN UNI73MART1_DCappl ON (XF_DC_ref.KEYVAL = UNI73MART1_DCappl.KEYVAL) WHERE (tbluniDCappl.DECSN <> UNI73MART1_DCappl.DECSN)
Try this with proper concatenation of the Nz expressions:
strSQL = "INSERT INTO ERROR_TABLE (ORACLE_FIELD, TRANSFORM_FIELD) SELECT " & MatchValues!ORACLE_TABLE_NAME & "." & MatchValues!FieldName & ", " & MatchValues!TRANSFORM_TABLE_NAME & "." & MatchValues!FieldName
strSQL = strSQL & " FROM " & MatchValues!TRANSFORM_TABLE_NAME & " INNER JOIN " & MatchValues!xfTableName
strSQL = strSQL & " ON " & MatchValues!TRANSFORM_TABLE_NAME & "." & MatchValues!SourceField1 & " = " & MatchValues!xfTableName & "." & MatchValues!ReferenceField1 & ""
strSQL = strSQL & " AND " & MatchValues!TRANSFORM_TABLE_NAME & "." & Nz(MatchValues!SourceField2, MatchValues!SourceField1) & " = " & MatchValues!xfTableName & "." & Nz(MatchValues!ReferenceField2, MatchValues!ReferenceField1) & ")"
strSQL = strSQL & " INNER JOIN " & MatchValues!ORACLE_TABLE_NAME & " ON (" & MatchValues!xfTableName
strSQL = strSQL & ".KEYVAL = " & MatchValues!ORACLE_TABLE_NAME & ".KEYVAL)"
strSQL = strSQL & " WHERE (" & MatchValues!TRANSFORM_TABLE_NAME & "." & MatchValues!FieldName
strSQL = strSQL & " <> " & MatchValues!ORACLE_TABLE_NAME & "." & MatchValues!FieldName & ")"
Pull the call to Nz out of the SQL. The two fields in question exist in the VBA context and so should be checked within the VBA code, not embedded in the SQL string.
strSQL = strSQL & " AND " & MatchValues!TRANSFORM_TABLE_NAME & "." Nz( MatchValues!SourceField2 , MatchValues!SourceField1) & " = " & MatchValues!xfTableName & "." & Nz( MatchValues!ReferenceField2 , MatchValues!ReferenceField1)
When NULL is concatenated with a string using &, null is just converted to a blank string. So the expression ".Nz(" & MatchValues!SourceField2 & "," & MatchValues!SourceField1 & ") = " & MatchValues!xfTableName & ".Nz(" & MatchValues!ReferenceField2 & "," & MatchValues!ReferenceField1 & ")" would simply produce the string value ".Nz(, SourceField1Name) = tablename.Nz(,ReferenceField1Name)... which is bad SQL syntax. I think Nathan_Sav was trying to point this out, but not very clear about it.
Hint 1: You should always debug an SQL statement built in code by printing out the actual SQL statement. You should have included that in your question.
Hint 2: Try using the VBA line continuation character _

Update function with case SQL and VBA

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"