LIKE query to find column values that are substrings of a longer string - sql

I want to use this code to find a value in field PID where it may exist anywhere in field MP_PID but my SQL is not catching them. No errors are thrown. What am I doing wrong?
It is comparing values from text fields in both recordsets.
Thanks
TMA
strPID = "DELETE * FROM tblPID WHERE PID Like '*" & !MP_PID & "*';"
If I use:
strPID = "DELETE * FROM tblPID WHERE PID = '" & !MP_PID & "';"
It works fine for exact matches.
Access 2007 DAO
What is wrong with my like statement? Thanks!

LIKE expressions are used to identify records where the value on the left side of the LIKE operator contains a string (or pattern of characters) represented by the wildcard string on the right side of the LIKE operator.
In your case
... '0123456A' LIKE '*0000623E 0123456A*'
will return False because the left side does not contain the entire string on the right side.
What you really want is
... '0000623E 0123456A' LIKE '*0123456A*'
which means that you need the MP_PID value on the left side of the LIKE operator.
To do that correctly (i.e., with a parameterized query) would look something like this:
Option Compare Database
Option Explicit
Sub LikeTest()
' test data
Dim MP_PID As String
MP_PID = "0000623E 0123456A"
Dim cdb As DAO.Database
Set cdb = CurrentDb
Dim qdf As DAO.QueryDef
Set qdf = cdb.CreateQueryDef("", _
"PARAMETERS [LongerText] TEXT(255);" & _
"DELETE * FROM tblPID WHERE [LongerText] LIKE '*' & PID & '*'")
qdf!LongerText = MP_PID
qdf.Execute dbFailOnError
Debug.Print qdf.RecordsAffected & " record(s) deleted."
Set qdf = Nothing
Set cdb = Nothing
End Sub

PID is most likely a numeric field and you use the LIKE operator which traverses string values. Try converting numeric value to string:
strPID = "DELETE * FROM tblPID WHERE CSTR(PID) Like '*" & !MP_PID & "*';"
Alternatively, concatenate an empty length string value to numeric value (similar to converting textbox numeric value to string by concatenating asterisks and quotes):
strPID = "DELETE * FROM tblPID WHERE PID & '' Like '*" & !MP_PID & "*';"

Ok Gord and Parfait. You both got me on the correct path and yes I did have it back asswards. Here is what I used to create a delete query:
strDelMP = "DELETE tblPID.* FROM tblPID INNER JOIN tblMgtPlan ON tblMgtPlan.MP_PID Like '*' + tblPID.PID + '*';"
db.Execute (strDelMP)
Thanks!

Related

Data type mismatch in criteria expression SQL Select In Access

Dim db As Database
Dim rrs As Recordset
Dim strselect As String
Set db = CurrentDb
strselect = "SELECT [Stok Pembelian] FROM t_databarang WHERE [ID Barang]= '" & Me.Text7 & "'"
Set rrs = db.OpenRecordset(strselect)
Me.Label1.Caption = rrs![Stok Pembelian]
I have a project from my school. I'm beginers and i'm so confused about my Access. I think that code it's correct, but there's an error "Data type mismatch in criteria expression." I already search much articles about how tow to fix it but not found. Please, help me.
Your id is most likely a number, thus no quotes:
strselect = "SELECT [Stok Pembelian] FROM t_databarang WHERE [ID Barang]= " & Me!Text7.Value & ""
Try to convert the textbox value into a double or int...
Dim Text7a as Double
Text7a = CLng(Me.Text7) 'Beware of rounding with Long Integers
Now use the alias Text7a for:
strselect = "SELECT [Stok Pembelian] FROM t_databarang WHERE [ID Barang]= '" & Me.Text7a & "'"
Check data types!
Like "Long Text do not match Number data type." Do it both them same data type on your database design

Using a VBA variable in SELECT Sql statement

Is their a way to use a declared VBA variable in a SELECT Sql statement as follows (I have a table called myTable and i want to set the referenced field by passing the declared string myVar) :
e.g passVar("English")
NB: Am using Microsoft Access
Private Function passVar(myVar as string)
Dim db As Database
Dim qdf As DAO.QueryDef
Dim stmnt As String
Set db = CurrentDb()
Set qdf = db.QueryDefs("SelectSubjectQuery")
stmnt = "SELECT [myTable].[myVar] = " &Chr$(34) & myVar & Chr$(34) & _
//other SQL statements go here
qdf.SQL = stmnt
End Function
Each time i run the query a dialog box appears asking for the value of mytable.myvar instead of passing myvar i.e Eglish as the referenced field on myTable.
Yes, build the SQL statement as a string like this:
stmnt = "SELECT " & [myTable] & "." & [myVar] & " = " &Chr$(34) & myVar & Chr$(34) & _
VBA should then fill in the names for MyTable and MyVar when the code is run and the string is built.
stmnt = "SELECT [myTable]." & myVar & _
Got it to working by writing as above (no need for the equals sign as the string is passed through the function). Thanks for the insight #rcfmonarch

Data type mismatch Acess 2010 VBA

I get a Data type mismatch error when I try to run the following code:
Dim myString As String
Dim rs As Recordset
sSQL = "SELECT * FROM KLIST WHERE KLIST = " & Me.bleh
Set rs = CurrentDb.OpenRecordset(sSQL)
myString = rs.Fields("DATEK")
The "bleh" field is a normal text field in a form. The field "KLIST" in the "KLIST" table is also a text field, containing numbers.
Does the fact that i enter numbers in the text field in the form change the format of the field? And if it does, how can I compare them in the WHERE statement.
Thanks.
As follow up from comments, this one works
sSQL = "SELECT * FROM KLIST WHERE TRIM(KLIST) = '" & TRIM(Me.bleh) & "'"
also you may want to see this on how to use VBA variables in SQL statements for different data types: Global Variables in SQL statement
If KLIST is a text column, you must add string delimiters (single quotes in SQL):
SELECT * FROM KLIST WHERE KLIST = '123'
In VBA
sSQL = "SELECT * FROM KLIST WHERE KLIST = '" & Me.bleh & "'"
A single quote within a string in SQL can be escaped by doubling the quote:
SELECT * FROM KLIST WHERE KLIST = 'that''s it'
Use the Replace function in VBA to achieve this:
sSQL = "SELECT * FROM KLIST WHERE KLIST = '" & Replace(Me.bleh, "'", "''") & "'"

Store a sql select statement, ran from VBA, in a numeric variable

I'm working on creating a dynamic pass-through query and in order to do so I first need to query my local db and get an ID.
This ID is what I will put into my pass-through query for my WHERE clause of the query.
My string:
getCorpID = "SELECT corpID " & _
"FROM dbo_corp " & _
"WHERE name = " & Forms.frmMain.Combo4.Value
I'm then trying to do something akin to:
CorpID (integer) = docmd.runsql (getCorpID)
I realize, however that docmd runsql doesn't work with select statements, or return a value even. What can I use to run my string
getCorpId
as sql and store the result (It will only be one result, every time.. one number) in my variable CorpID
Thank you.
Consider about using Recordset :
Dim dbs As DAO.Database
Dim rsSQL As DAO.Recordset
Dim getCorpID As String
Dim CorpID
Set dbs = CurrentDb
getCorpID = "SELECT corpID " & _
"FROM dbo_corp " & _
"WHERE name = " & Forms.frmMain.Combo4.Value
Set rsSQL = dbs.OpenRecordset(getCorpID , dbOpenSnapshot)
rsSQL.MoveFirst
CorpID = rsSQL.Fields("corpID")

Use a ComboBox Value as part of an SQL Query? (MS Access 2010-2013)

I have a Database that we use to create Bills of Materials from Tags in AutoCAD. Because of the nature of this, I need to create 3 separate queries. One for our "Steel", one for our
"Non-Steel", and one for our "Uncut Tubes".
The SQL for the Queries is as follows:
Steel:
SELECT DISTINCTROW Sum([CUT-LENGTH-WEIGHT]) AS [SumOfCUT-LENGTH-WEIGHT], Sum([CUT-SHEET-WEIGHT]) AS [SumOfCUT-SHEET-WEIGHT], Sum([TOTAL-SHEETING-WEIGHT]) AS [SumOfTOTAL-SHEETING-WEIGHT], Sum([TOTAL-ITEM-WEIGHT]) AS [SumOfTOTAL-ITEM-WEIGHT]
FROM [13-1302 Cut-Lengths];
Non-Steel:
SELECT tbl2013BOM.fJobID, Sum(tbl2013BOM.fWeight) AS SumOffWeight
FROM tbl2013BOM
GROUP BY tbl2013BOM.fJobID
HAVING (((tbl2013BOM.fJobID)=23));
Uncut Tubes:
SELECT DISTINCT [13-1302 Cut-Lengths].[TOTAL-LENGTH-WEIGHT], [13-1302 Cut-Lengths].MATERIAL, [13-1302 Cut-Lengths].ORDER
FROM [13-1302 Cut-Lengths]
ORDER BY [13-1302 Cut-Lengths].ORDER;
I have a ComboBox that chooses the Job Number (For Main and Uncut Tubes, e.g. 13-1302) and a Textbox that displays the JobID (For Non-Steel).
Is there a way that I can set up the SQL shown above to look at the ComboBox and TextBox Values, instead of me having to change them by hand?
EDIT
I figured it all out now. (Thank you Elias)
Basically, I cannot use a Field on a table as a RecordSource in SQL, in other words, Combo26 cannot be the Table in an SQL Query. HOWEVER, what CAN be done is to use VBA to inject that value into an SQL Definition, then use that definition as a Recordsource.
I will place the code for my Button below so anyone can use it and reference it:
Private Sub Command27_Click()
Dim dbs As Database
Dim rstSQL As DAO.Recordset
Dim strSQL As String
Dim strSQL2 As String
Dim strSQL3 As String
Dim Field As String
Set dbs = CurrentDb
Field = [Forms]![frmBOM_Combined]![Text26].[Value]
strSQL = "SELECT DISTINCTROW Sum([CUT-LENGTH-WEIGHT]) AS [SumOfCUT-LENGTH-WEIGHT], Sum([TOTAL-SHEETING-WEIGHT]) AS [SumOfTOTAL-SHEETING-WEIGHT], Sum([TOTAL-ITEM-WEIGHT]) AS [SumOfTOTAL-ITEM-WEIGHT] FROM " & "[" & [Forms]![frmBOM_Combined]![Text26].[Value] & "]" & ";"
strSQL2 = "SELECT tbl2013BOM.fJobID, Sum(tbl2013BOM.fWeight) AS SumOffWeight FROM tbl2013BOM GROUP BY tbl2013BOM.fJobID HAVING (((tbl2013BOM.fJobID)= " & [Forms]![frmBOM_Combined]![Combo25].[Value] & "));"
strSQL3 = "SELECT DISTINCT [TOTAL-LENGTH-WEIGHT], [MATERIAL], [ORDER] FROM " & "[" & [Forms]![frmBOM_Combined]![Text26].[Value] & "]" & " ORDER BY [ORDER];"
Debug.Print strSQL
Debug.Print strSQL2
Debug.Print strSQL3
DoCmd.OpenForm ("frmEstWeight")
Forms!frmEstWeight.RecordSource = strSQL
Forms!frmEstWeight.frmTestBomWeight.Form.RecordSource = strSQL2
Forms!frmEstWeight.frmTotalLengthWeight.Form.RecordSource = strSQL3
End Sub
This is working exactly as it should with no errors or anything.
This is within a form correct?
If so, replace the manual values you put in with
REST OF THE QUERY HERE " & Me!Controlname.value & " REST OF THE QUERY HERE
and if you are using something with a control source then just reset the control source value.
me!ControlWithResult.control source = "SELECT tbl2013BOM.fJobID, Sum (tbl2013BOM.fWeight) AS SumOffWeight
FROM tbl2013BOM
GROUP BY tbl2013BOM.fJobID
HAVING (((tbl2013BOM.fJobID)=" & me!controlname.value & "));"
For Non-Steel try:
On the VBA for the popup form
me!Combo25.rowsource = "SELECT tbl2013BOM.fJobID, Sum(tbl2013BOM.fWeight) AS SumOffWeight
FROM tbl2013BOM
GROUP BY tbl2013BOM.fJobID
HAVING (((tbl2013BOM.fJobID)=" & forms!MAINFORMNAME! &"));