Data type missmatch in criteria expression - sql

Is there any wrong in this SQL statement in VBA:
myConnection.Execute "update item_gallery set quantity = 'qtToTotal' where item = 'Desc' and gallery ='Gallery_Name'"
where
qtToTotal = qtTo + qtFrom
While Not myRecordSetItem.EOF
If !item_ID = myRecordSetItem.Fields("item_ID").Value Then
Desc = myRecordSetItem.Fields("Desc").Value
End If
myRecordSetItem.MoveNext
Wend
While Not myRecordSetGallery.EOF
If !To = myRecordSetGallery.Fields("Gallery_ID").Value Then
Gallery_Name = myRecordSetGallery.Fields("Gallery_Name").Value
End If
myRecordSetGallery.MoveNext
Wend
it always give me the message :
"data type missmatch in criteria expression"

This:
myConnection.Execute "update item_gallery set quantity = 'qtToTotal' where item = 'Desc' and gallery ='Gallery_Name'"
where
qtToTotal = qtTo + qtFrom
Looks like it should read more like this (but I'm not 100% as I have some questions to ask):
myConnection.Execute "UPDATE item_gallery" _
& " SET quantity = qtToTotal" _
& " WHERE item = Desc" _
& " AND gallery = Gallery_Name" _
& " AND qtToTotal = (qtTo + qtFrom)"
My guess is you're getting this error because you've surrounded what look like field names in single quotes ('), which is what you do when you're telling SQL that you're wanting a piece of text rather than one of the fields in your database.
Examples of when to use single quotes:
...when you want to refer to just a piece of text in a field formatted as text:
"SELECT * FROM tblNames WHERE FirstName = 'John'".
...when you want to refer to text that's currently in a field on an open form that is formatted as text:
"SELECT * FROM tblNames WHERE FirstName = '" & Me.txtFirstName & "'".
But in your case it looks like you want a field from the underlying tables, so you don't need any single quotes around the field name.
Your quantity field sounds like it could well be a numeric field and you've essentially asked it to try and put the piece of text "qtToTotal" in the quantity field, which it won't be able to do if that field is only setup to accept numbers.
A few questions though as I suspect there might be more problems here (and I'll update this based on your answers):
Are all these fields...
quantity
qtToTotal
item
Desc
gallery
qtToTotal
qtTo
qtFrom
...located in the table item_gallery?
If they're not then you need to create JOIN(s) in your SQL statement between the item_gallery table and whatever table(s) the other fields come from using a field that matches/relates the records from both tables.
What is the data type for each of these fields?
Where you've used an = between 2 fields, are both those fields the same data type? If not it will cause a mismatch.
Also: I'd advise against using "Desc" as a field name as DESC is a word reserved for "descending order" in an ORDER BY clause in SQL.

Related

Passing multiple Excel cell values to SQL query WHERE clause without referencing other queries

I have an SQL view, MyView, containing the column ID of type nvarchar.
I wish to create an Excel query which:
takes the values from a column in an Excel sheet,
composes a string corresponding to a WHERE clause for the ID column,
calls the SQL query using this parameter string.
As far as I can tell, I am trying to achieve something very analogous to
Excel cell Value as SQL query where statement
My solution is working fine on my own computer. However, when I try to share my solution with a colleague who has the same reading permissions for the database, I end up with a 'query referencing another query' problem which throws a formula.firewall error, and no data is loaded.
My solution is as follows:
I have created a data connection, Parameters, from the column named ID in Excel which contains my ID values:
let
Source = Excel.CurrentWorkbook(){[Name="Parameters"]}[Content],
#"Changed type" = Table.TransformColumnTypes(Source,{{"ID", type text}})
in
#"Changed type"
Next, I create my parameter string as a new data source, fnGetParameters:
let
Source = Excel.CurrentWorkbook(){[Name="Parameters"]}[Content],
AddString = Table.AddColumn(Source, "Custom", each "ID = " & "'" & [ID] & "' OR "),
RemoveID = Table.SelectColumns(AddString,{"Custom"}),
Custom = Text.Combine(RemoveID[Custom], ""),
Parameter = Text.Start(Custom,Text.Length(Custom)-4)
in
Parameter
which creates a nice string looking like e.g. 'ID = '1' OR ID = '2' OR ID = '3'' depending on the values in the column ID in Parameters.
Finally, I try to create my query:
let
Source = Sql.Database("MyServer", "MyDatabase",[Query="
SELECT *
FROM [MyDatabase].[dbo].[MyView]
WHERE " & fnGetParameters])
in
#"Source"
Incidentally, when removing the WHERE clause from the code above, it works fine on any computer:
let
Source = Sql.Database("MyServer", "MyDatabase",[Query="
SELECT *
FROM [MyDatabase].[dbo].[MyView]"])
in
#"Source"
so it is somehow the addition of the parameter string which causes an error.

Access Subform SourceObject Set to Query updated with SQL - Column Order and Width?

I have an Access form with different functions users can do. They are pulling lists of data, all from 1 table. Based on different filters or operations they want to do, I dynamically construct the SQL, use that to update the query defs of a query, and then set the subform object to that updated query. The problem is that the one I update the subform source object to the query, I need the columns that show to be in the order of the query.
This is the code I use, at different points of use on the form, depending on if they are interacting with a combo box, entering a filter into a textbox control on the main form, and I use similar code to set the default sql/query defs on load of the form. Why don't the columns always show in the same order as the sql that was updated to the query's definition?
Dim fsql As String
fsql = "SELECT table1.field1, table1.field2, table1.field3, table1.field4, table1.field5, table1.field6, table1.field7 " & _
"FROM tblVFileImport "
If Nz(Me.cboFilterA, "") = "" Then
fsql = fsql & "ORDER BY table1.field2, table1.field3 "
Else
fsql = fsql & "WHERE table1.field6 = '" &Me.cboFilterA & "' "
fsql = fsql & "ORDER BY table1.field4, table1.field5 "
Me.cmdExtrabutton.Visible = True
End If
CurrentDb.QueryDefs("qrySubformSpecs").SQL = fsql
Forms!frmDoStuff.Form.frmDoStuff_SubResults.SourceObject = ""
Forms!frmDoStuff.Form.frmDoStuff_SubResults.SourceObject = "Query.qrySubformSpecs"
The columns get in order some times, but not consistently.
I also want to fit the columns a small as they can, fitting the contents of their respective data, if that's possible. The column fit is not as big of a deal, because the user can select the left corner and then double-click between the columns if they really need to. The order of the columns is definitely more important here.
If anyone knows how to accomplish this, I would really love the help. Thanks!
FWIW, the backend is SQL, so this is all coming from 1 big linked table. The performance is quick and not an issue, but the column order is important and needing to work right.

What to do with VBA Query Result

I have a query within access that selects all the contacts for a particular company based on the CompanyID Field. And on my form i have a selection of labels of which will be populated with the query result. However i'm a little stuck on how i should populate the labels, as there will be more than one contact returned from the query..
The Query
ConactData = "SELECT * FROM Contacts WHERE CompanyID = " & CompanyValue & ";"
Obviously i can do
Set rst = CurrentDb.OpenRecordset(ContactData, dbOpenSnapshot)
Me.lblTitle.Caption = rst!Title
Me.lblFirstName.Caption = rst!FirstName
Me.lblLastName.Caption = rst!LastName
Me.lblEmail.Caption = rst!Email
Me.lblMobileNumber.Caption = rst!MobileNumber
But this will just select the first result from the table, how then, can i move onto the next result? If i'm right in thinking the MoveNext method will simply go to the next record in the table, not the query result?
Why use labels? Just build the form bound to the table.
Then in your code go:
Me.RecordSource = "SELECT * FROM Contacts WHERE CompanyID = " & CompanyValue & ";"
This means you don’t need a bunch code to fill out the form, it is done for you. And your example would not allow editing of data either. To write a bunch of code when all the display of data is automatic is a waste of developer time and resources.
In fact, why not leave the form bound to the table, and then use a where clause to open the form
eg:
docmd.openform "frmContacts",,,"CompanyID = " & CompanyValue
So it not clear why you writing all that code and doing handstands - it simply not required.

SQL statement for combobox row source

I'm trying to define a SQL statement to use as the Row Source for a ComboBox on an MSAccess form. The SQL should select records from a table tblI where a particular table field matches a variant parameter varS set by the user; however, if varS is Null or not present in another table tblS, the SQl should select all records in tblI.
I can code the first parts of this (varS matches or is null):
SELECT tblI.ID, tblI.S FROM tblI WHERE ((tblI.S = varS) OR (varS Is Null)) ORDER BY tblI.ID;
Where I'm struggling is incorporating the final element (varS not present in tblS). I can code a test for the absence of varS in tblS:
Is Null(DLookup("[tbls.ID]","tblS","[tblS.ID]= " & varS))
but I can't work out how to incorporate this in the SQL statement. Should this work?
SELECT tblI.ID, tblI.S FROM tblI WHERE tblI.S = varS OR varS Is Null OR DLookup("[tbls.ID]","tblS","[tblS.ID]= " & varS) Is Null ORDER BY tblI.ID;
When run as a query it returns every record in tblS no matter the value of varS.
Table structure:
tblI contains 2 fields, Autonumber ID and Long S
tblS contains 1 field, Autonumber ID
My own approach to this problem would be something like this:
Private Sub SetComboSource(vID as Variant)
Dim sSQL as String
sSQL = "SELECT tblI.ID, tblI.S " & _
"FROM tblI "
If IsNull(vID) = False Then
If IsNumeric(vID) = True Then
If DCount("ID", "tblS", "ID = " Clng(vID)) > 0 Then
sSQL = sSQL & "WHERE tblI.S = " & CLng(vID)
End If
End If
End If
sSQL = sSQL & " ORDER BY tblI.ID"
Me.cboComboBox.RowSource = sSQL
End Sub
BTW, I recommend you give your tables and fields more descriptive names and then use aliasing in your SQL, especially for table names. I also think it's best to avoid using Variant variables. I usually use Longs for something like this and I take a value less than 1 to mean that the user didn't select anything, or selected ALL, or whatever meaning you want to derive from it. In other words, my ID's are always a number greater than zero and an ID of less than 1 in a variable means that the ID is empty. Which I use as a signal to create a new record, or to return all records, or whatever meaning you want to derive from it in the given context.
The following should work;
SELECT tblI.ID, tblI.S
FROM tblI
WHERE tbl.ID=varS
OR varS NOT IN(SELECT ID from tblS)

MS Access multi field search with empty fields

I have a problem very similar to this one, but I just can't seem to solve it!
In MS Access (2003), I want to search a table based on entries in a number of fields, some of which may be empty.
I have:
text fields
date fields
integer fields, and
a memo field (but we can probably not bother searching this one if it is difficult).
They map onto a table exactly.
I am trying to create a query that will return matching rows when data is entered into one or more of these fields, but some fields can be left blank. How the heck do I do this?
A query like the one on the linked question works for text fields, but what do I do about the number fields, date fields (and possibly even the memo field)?
To give a clear example, the following code block works for TextField1, but not NumberField1:
PARAMETERS [Forms]![SearchForm]![FilterTextField1] Text ( 255 ), [Forms]![SearchForm]![FilterNumberField1] Text ( 255 );
SELECT Table1.[TextField1], Table1.[NumberField1], Table1.[TextField2], Table1.[TextField3], Table1.[DateField1], Table1.[DateField2], Table1.[DateField3]
FROM Table1
WHERE (Len([Forms]![SearchForm]![FilterTextField1] & '')=0 OR Table1.[TextField1] Like '*' & [Forms]![SearchForm]![FilterTextField1] & '*') AND (Len([Forms]![SearchForm]![FilterNumberField1] & '')=0 OR Table1.[NumberField1] Like '*' & [Forms]![SearchForm]![FilterNumberField1] & '*');
I do hope you can help. I'm sure I'm missing something really obvious, but for some reason my brain feels like it is leaking out of my ears at the moment.
Thank you!
If you need it, this is the basic design of the relevant entities:
Table1
SomePrimaryKeyWeDontCareAboutRightNow
TextField1
TextField2
TextField3
NumberField1
DateField1
DateField2
DateField3
MemoField1
SearchForm
FilterTextField1
FilterTextField2
FilterTextField3
FilterNumberField1
FilterDateField1
FilterDateField2
FilterDateField3
FilterMemoField1
You can check fo null values or cast to string
You could certainly spend a great deal of time crafting a huge and very hard to debug SQL query for this, or just jump into VBA and write some code to construct just the SQL you need.
VBA is there just for these kinds of scenario, where something is either impossible or becoming too complex to do otherwise.
With VBA, you can use an initial SELECT query that collect all the data, and then construct a WHERE clause based on the content of your search form to filter it.
For instance, I have a form like this, that allows the user to enter any criteria to filter a list of prices:
Some code to implement this could look like:
' Call this whenever the use click the Apply button '
Private Sub btApply_Click()
' Construct the filter '
Dim filter As String
If Not IsBlank(cbSupplierID) Then
If Not IsBlank(filter) Then filter = filter & " AND "
filter = filter & "(SupplierID=" & cbSupplierID & ")"
End If
If Not IsBlank(txtPartNumber) Then
If Not IsBlank(filter) Then filter = filter & " AND "
filter = filter & "(PartNumber LIKE '*" & txtPartNumber & "*')"
End If
If Not ckShowLocked Then
If Not IsBlank(filter) Then filter = filter & " AND "
filter = filter & "(NOT PriceLocked)"
End If
' ... code snipped, you get the jest ... '
' Now re-construct the SQL query '
Dim sql As String
sql = "SELECT * FROM Price"
If Not IsBlank(filter) Then
sql = sql & " WHERE " & filter
End If
SubForm.Form.RecordSource = sql
End Sub
It may seem like a lot of code, but each block only does one thing, and it's a lot easier to debug and maintain than cramming everything into a query.