Why does my SQL query return two different results? - sql

I'm using SQL in MS Access to retrieve data from a table but depending on whether I run a query or use VBA, I get two different results for the same query.
Quite simply, I want the max value from a single column in a table. The trouble is, I think, is that the column datatype is text? The table consists, primarily, of 6 digit numbers interspersed with other formats such as 'xx-xxxxx'.
Firstly, I need to be able to do this in VBA, so I have this:
Private Function Create() As String
Dim rs As New ADODB.Recordset
Dim cn As New ADODB.Connection
Dim strSQL As String
Set cn = CurrentProject.Connection
cn.CursorLocation = adUseClient
strSQL = "SELECT Max(par.PN) AS PN FROM par WHERE ((PN Between CLng('100000') And CLng('999999')) And (PN Not Like '##-#####'));"
Set rs = cn.Execute(strSQL)
If (rs.RecordCount > 0) Then
'Create = rs("PN")
Debug.Print rs("PN")
End If
End Function
The result is 10-0000 so my first though is that the query is wrong so I head off over to the query builder and enter:
SELECT Max(par.PN) AS PN
FROM par
WHERE ((PN Between CLng('100000') And CLng('999999')) And (PN Not Like '##-#####'));
which returns 745864 when I run it. So from this I can see there is something awry here.
Now, the other thing that strikes me is that I don't think I should need And (PN Not Like '##-#####') in order to get a six digit number as I would have though WHERE ((PN Between CLng('100000') And CLng('999999')) would have been sufficient...
I have a suspicion that this is because the numbers are stored as text and because of this the between function will not work on text - if this is indeed true, I would have further expected that the CLng function would have converted successfully to number in order for this query to work.
In any case, I need to be able to get the latest six digit number using vba. Can anyone shed any light on where the problem lies?
Thanks

ADO SQL uses the ANSI 92 version of the LIKE operator (allowed wildcards: _ for a single character, % for multiple characters).
MS Access and DAO use a different form of LIKE operator (see this MSDN page for the allowed wildcards)
If you want to use such a comparison, I recommend you switch to DAO (if you don't have a specific reason to use ADO)
An alternative approach (and the one that would have my preference) would be casting PN to an actual number:
SELECT Max(CLng(Replace(par.PN, "-", ""))) AS PN
FROM par
WHERE CLng(Replace(par.PN, "-", "")) Between 100000 And 999999

Related

Using SQL Wildcards with LINQ

I have a question about using LINQ to access a Database and trying to make use of it's version of accessing the LIKE comparison operator.
I know that LINQ has .Contains(), .StartsWith(), and .EndsWith() as comparison methods. However I am wondering if there is a way to programatically imcorporate SQL Wildcards into a LINQ statement without explicitly using these query operators. Let me explain my situation.
I am writing a program that accesses a database, and part of the program is a search window which the user can use to help them find specific database data. I would like to try and incorporate SQL Wildcards into the textbox fields for these search pages.
For example if a user enters the input 17% I'd want the program to check for anything in that specific column that starts with a 17. The same is true with %17 and 17 where I'd want it to search for columns that end with, and contain the values.
Currently, this is the code I have for my search method:
Public Function Data_Search(sData As List(Of String), DB As CustomDataContext) As DataGridView
Dim gridData As New DataGridView
Dim query = From p In DB.Parts
Select p.Part_Number, p.Part_Description, p.Supplier.Supplier_Name
for i = 0 To sData.Count - 1
If Not sData(i).ToString() = "" Then
Select Case i
Case 0
Dim partNum As String = sData(i).ToString()
query = query.Where(Function(x) x.Part_Number.Contains(partNum))
Case 1
Dim description As String = sData(i).ToString()
query = query.Where(Function(x) x.Part_Description.Contains(description))
Case 2
Dim supp As String = sData(i).ToString()
query = query.Where(Function(x) x.Supplier_Name.Contains(supp))
End Select
End If
Next
gridData.DataSource = query.ToList()
Return gridData
End Function
So right now I am trying to see if there is a way for me to modify the code in a way that doesn't essentially involve me putting a substring search into each Case section to determine if I should be using StartsWith(), Contains(), or EndsWith.
Thanks for your time.
If you are using LINQ to SQL, and you are talking to Microsoft SQL Server, then you can use SQLMethods.Like to implement SQL LIKE:
query = query.Where(Function(x) SQLMethods.Like(x.Part_Number, partNum))

Retrieving the Query used for a OleDBCommand

I'm currently using the following VB code to make a query against an Access Database, I would like to know is it possible to obtain what the SELECT statement that is being run and send that output to the console.
Dim QuestionConnectionQuery = New OleDb.OleDbCommand("SELECT Questions.QuestionID FROM Questions WHERE Questions.QuestionDifficulty=[X] AND ( Questions.LastDateRevealed Is Null OR Questions.LastDateRevealed < DateAdd('d',-2,Date() ) AND Questions.LastUsedKey NOT LIKE ""[Y]"" );", QuestionConnection)
QuestionConnectionQuery.Parameters.AddWithValue("X", questionDifficulty.ToString)
QuestionConnectionQuery.Parameters.AddWithValue("Y", strDatabaseKey)
Right now when I try to use: Console.WriteLine("Query: " & QuestionConnectionQuery.ToString)
I only get this:
Loop Question #1
Query: System.Data.OleDb.OleDbCommand
The short version comes down to this:
QuestionConnectionQuery.ToString
The QuestionConnectionQuery object is much more than just the text of your command. It's also the parameters, execution type, a timeout, and a number of other things. If you want the command text, ask for it:
QuestionConnectionQuery.CommandText
But that's only the first issue here.
Right now, your parameters are not defined correctly, so this query will never succeed. OleDb uses ? as the parameter placeholder. Then the order in which you add the parameters to the collection has to match the order in which the placeholder shows in the query. The code in your question just has X and Y directly for parameter placeholders. You want to do this:
Dim QuestionConnectionQuery AS New OleDb.OleDbCommand("SELECT Questions.QuestionID FROM Questions WHERE Questions.QuestionDifficulty= ? AND ( Questions.LastDateRevealed Is Null OR Questions.LastDateRevealed < DateAdd('d',-2, Date() ) AND Questions.LastUsedKey NOT LIKE ? );", QuestionConnection)
QuestionConnectionQuery.Parameters.Add("?", OleDbType.Integer).Value = questionDifficulty
QuestionConnectionQuery.Parameters.Add("?", OleDbType.VarChar, 20).Value = strDatabaseKey
I had to guess at the type and lengths of your parameters. Adjust that to match the actual types and lengths of the columns in your database.
Once you have made these fixes, this next thing to understand is that the completed query never exists. The whole point of parameterized queries is parameter data is never substituted directly into the sql command text, not even by the database engine. This keeps user data separated from the command and prevents any possibility of sql injection attacks.
While I'm here, you may also want to examine the WHERE conditions in your query. The WHERE clause currently looks like this:
WHERE A AND ( B OR C AND D )
Whenever you see an AND next to an OR like that, within the same parenthetical section, I have to stop and ask if that's what is really intended, or whether you should instead close the parentheses before the final AND condition:
WHERE A AND (B OR C) AND D
This will fetch the command text and swap in the parameter values. It isnt necessarily valid SQL, the NET Provider objects haven't escaped things yet, but you can see what the values are and what the order is for debugging:
Function GetFullCommandSQL(cmd As Data.Common.DbCommand) As String
Dim sql = cmd.CommandText
For Each p As Data.Common.DbParameter In cmd.Parameters
If sql.Contains(p.ParameterName) AndAlso p.Value IsNot Nothing Then
If p.Value.GetType Is GetType(String) Then
sql = sql.Replace(p.ParameterName,
String.Format("'{0}'", p.Value.ToString))
Else
sql = sql.Replace(p.ParameterName, p.Value.ToString)
End If
End If
Next
Return sql
End Function
Given the following SQL:
Dim sql = "INSERT INTO Demo (`Name`, StartDate, HP, Active) VALUES (#name, #start, #hp, #act)"
After parameters are supplied, you can get back this:
INSERT INTO Demo (`Name`, StartDate, HP, Active) VALUES ('johnny', 2/11/2010 12:00:00 AM, 6, True)
It would need to be modified to work with OleDB '?' type parameter placeholders. But it will work if the DbCommand object was created by an OleDBCOmmandBuilder, since it uses "#pN" internally.
To get or set the text of the command that will be run, use the CommandText property.
To print the results, you need to actually execute the query. Call its ExecuteReader method to get an OleDbDataReader. You can use that to iterate over the rows.
Dim reader = QuestionConnectionQuery.ExecuteReader()
While reader.Read
Console.WriteLine(reader.GetValue(0))
End While
reader.Close()
If you know the data type of the column(s) ahead of time, you can use the type-specific methods like GetInt32. If you have multiple columns, change the 0 in this example to the zero-based index of the column you want.

Access SQL How to select randomly a group of contiguous rows

can this be done, say I have rows (1,2,3,4,5) and I want to grab three rows, select one randomly and then get it's neighbors, so maybe the random selection is row (3), I can also grab (2,4) if I wanted its neighbors, do I just pick one at random and then look for the unique key before and after like this or can I do it all in one sql statement.
I was going to use ADO from excel to pull records (so VBA connects to access, opens a recordset with sql instructions and so on).
Hope I was clear!
I would love to just do this all in a SQL statement
I am not sure Access is capable of all the SQL commands such as SQL Server, so this may be a bit of a problem. If you have a primary key though, you can easly generate a Select query in VBA and then pass open recordset with this SQL.
Dim sSQL as String
Dim lRand as Long
Dim rs as ADODB.Recordset 'or DAO.Recordset'
lRand = VBA.Int(VBA.Rnd() * TableRecordCount) ' TableRecordCount is the number of records in the table that you need to get somehow'
sSQL = "SELECT * FROM TableName WHERE (ID>=" & lRand - 1 & " AND ID <=" & lRand + 1
set rs = CurrentDB.OpenRecordset(sSQL, ...)
I am now not absolutely sure of what you want to use and depending on ADODB or DAO choice, you need to open the recordset accordingly with wither Call rs.Open or Set rs = DB.OpenRecordset

Date Subtraction within Select Statement

I am currently working on an MS Access database, and am having problem with date subtraction.
Essentially I am trying to create a target date for example:
Target Date = Deadline - Lead Time
i.e. the lead time could be 30 days, therefore the target date should be 30 days prior to the deadline.
The code I am trying to use is this:
strSQL = "INSERT INTO dbo_DEALER_TASK ( Dlr_Number, Action_Id, Task_Id, Area_Id,
Task_Deadline_Date, Responsible_Person_Id, Alternate_Person_Id, Priority, Comment,
Suppress_Email, Dealer_Type ) "
strSQL = strSQL & "SELECT dbo_DEALER_ACTION.Dlr_Number, dbo_DEALER_ACTION.Action_Id,
qryAllTasksToAdd.Task_Id, qryAllTasksToAdd.Area_Id, Deadline_Date - Deadline_adjustment
AS 'Task_Deadline_Date', qryAllTasksToAdd.Person_Responsible_Id,
qryAllTasksToAdd.Alternate_Responsible_Id, qryAllTasksToAdd.Priority,
qryAllTasksToAdd.Comment, qryAllTasksToAdd.Suppress_Email,
qryAllTasksToAdd.Applies_To_Dealer_Type "
strSQL = strSQL & "FROM dbo_DEALER_ACTION LEFT JOIN qryAllTasksToAdd ON
(dbo_DEALER_ACTION.Dealer_Type = qryAllTasksToAdd.Applies_To_Dealer_Type) AND
(dbo_DEALER_ACTION.Action_Id = qryAllTasksToAdd.Action_Id) "
strSQL = strSQL & WHERE (((qryAllTasksToAdd.Task_Id)=" & Me.Task_Id & ") AND
((dbo_DEALER_ACTION.Date_Completed) Is Null));"
DoCmd.RunSQL strSQL
When the VBA code executes the statement, everything is updated correctly, except for the Task_Deadline_Date field, which is being left blank.
What is really confusing me though is if I run this SQL statement standalone it is working as expected. After trying a number of different ideas I tried to replace "Deadline_Date - Deadline_adjustment AS 'Task_Deadline_Date'" with a string literal date and the statement then worked fine
Does anybody have any ideas what is going wrong?
Thanks,
Chris
You have quoted the alias, you should not do that:
Deadline_Date - Deadline_adjustment AS Task_Deadline_Date
Not
Deadline_Date - Deadline_adjustment AS 'Task_Deadline_Date'
When you add the quotes, the name of the field is 'Task_Deadline_Date'
Depending on the data type of your date field and whether or not you are using SQL Server, you may need to use DateAdd, for example:
DateAdd("d",-[Deadline_adjustment],[Deadline_Date])
In Access' query designer, start with the version of your query which works and convert it to a parameter query.
WHERE
qryAllTasksToAdd.Task_Id=[which_id]
AND dbo_DEALER_ACTION.Date_Completed Is Null;
You can also add a PARAMETERS statement at the start of the query to inform the db engine about the data type of your parameter. Examples ...
PARAMETERS which_id Text ( 255 );
PARAMETERS which_id Long;
Once you get that query working, save it and give it a name. Then your VBA procedure can use that saved query, feed it the parameter value, and execute it.
Dim db As DAO.database
Dim qdf As DAO.QueryDef
Set db = CurrentDb
Set qdf = db.QueryDefs("YourQuery")
qdf.Parameters("which_id").value = Me.Task_Id
qdf.Execute dbFailOnError
Set qdf = Nothing
Set db = Nothing
This should be much easier than trying to recreate that SQL statement in VBA code each time you need to execute it.
It sounds like the data type of the column you are inserting in dbo_DEALER_TASK is not actually a datetime field.
I tried to replace "Deadline_Date - Deadline_adjustment AS 'Task_Deadline_Date'" with a string literal date and the statement then worked fine
If you mean '02/20/2012' (as you would correctly use on SQL Server, for example) then this shouldn't work in Access and only will if your output column is a text (= varchar/char)) data type. Date constants in Access are specified like #02/20/2012#
Please confirm the data type of Task_Deadline_Date in your output table.

how to replace text in a multifield value column in access

I've got a tablea such as below, I know its bad design having multifield value column but I'm really looking for a hack right now.
Student | Age | Classes
--------|------|----------
foo | 23 | classone, classtwo, classthree, classfour
bar | 24 | classtwo, classfive, classeight
When I run a simple select query as below, I want the results such a way that even occurrence of classtwo is displayed as class2
select student, classes from tablea;
I tried the replace() function but it doesnt work on multivalued fields >_<
You are in a tough situation and I can't think of a SQL solution for you. I think your best option would be to write a VB function that will take the string of data, parse it out (replacing) the returning you the updated string that you can update your data with.
I can cook up quite a few ways to solve this.
You can explode the mv by using Classes.Value in your query. This will cause one row to appear for each value in the query and thus you now can use replace on that. However, this will result in one separate row for each class.
So use this:
Select student, classes.Value from tablea
Or, for this example:
Select student, replace(classes.Value,"classtwo","class2") as myclass
from tablea
If you want one line, AND ALSO the multi value classes are NOT from another table (else they will be returning ID not text), then then you can use the following trick
Select student, dlookup("Classes","tablea","id = " & [id]) as sclasses
from tablea
The above will return the classes separated by a space as a string if you use dlookup(). So just add replace to the above SQL. I suppose if you want, you could also do replace on the space back to a "," for display.
Last but not least, if this those classes are coming from another table, then the dlookup() idea above will not work. So just simply create a VBA function.
You query becomes:
Select student, strClass([id]) as sclasses from tablea
And in a standard code module you create a public function like this:
Public Function strClass(id As Variant) As String
Dim rst As DAO.Recordset
If IsNull(id) = False Then
Set rst = CurrentDb.OpenRecordset("select Classes.Value from tableA where id = " & id)
Do While rst.EOF = False
If strClass <> "" Then strClass = strClass & ","
strClass = strClass & Replace(rst(0), "classtwo", "class2")
rst.MoveNext
Loop
rst.Close
Set rst = Nothing
End If
End Function
Also, if you sending this out to a report, then you can DUMP ALL of the above ideas, and simply bind the above to a text box on the report and put the ONE replace command around that in the text box control. It is quite likely you going to send this out to a report, but you did ask how to do this in a query, and it might be the wrong question since you can "fix" this issue in the report writer and not modify the data at the query level. I also think the replace() command used in the report writer would likely perform the best. However, the above query can be exported, so it really depends on the final goal here.
So lots of easy ways to do this.