Using VBA to remove the alias name from an SQL query string? - mysql

I have an SQL query string. In this string are multiple different columns of data, all coming from the same table. For simplicities sake, here is a short example: SELECT 'A'.'B', 'A'.'C', 'A'.'D'
Where 'A' is the alias name. My question is: Is there a way using VBA to take that query string, and remove all instances of the alias 'A' and just return the data columns 'B', 'C', 'D'?
Please no full code, I like starting points. I like to fill in the pieces on my own. It helps the learning process.

Recover the SQL under the QueryTable like this:
Recover SQL:
Range("A1").Select 'Your query worksheet
With Selection.QueryTable
queryText = .CommandText
End With
Then replace the aliases with LEFT, RIGHT, INSTR or RegExp object (if you want to learn something useful and quick use RegExp - regular expressions). If you need an example regex let me know in the comments. If you want to learn Regex in VBA I made a tutorial here.
Replace the query and refresh the QueryTable
Replace and refresh query
Range("A1").Select 'Your query worksheet
With Selection.QueryTable
.CommandText = queryText
.Refresh BackgroundQuery:=False
End With

Are you selecting straight from the table? Going straight from the table would give you the column name, unless you're performing some function in your query. Another option is:
Select [A] AS columnName, [B] AS ColumnName2, etc

Related

method to update table based on function output

I'm using an access function that loops through multiple record sets using case select statements and displays rows of strings in the VBA immediate window.
Can anyone suggest how I can learn about methods that might be used to update a table with the results that are currently displayed in the VBA immediate window?
So far, my searches have suggested that DoCmd.SQL might work.
Case Is = "1" ' 1 bottle
Debug.Print rsWCol!r4_wcol_outstring & rsBottl!bottleoutstring
displays the string below in the immediate window:
R41602T50 1 00 62 710 C 1120 9800 550 1 00S #135 0
I'd like to be able to use something like the following
Dim writeRecSQL As String ' used to append records to a temp table
writeRecSQL = "INSERT INTO tbl_R_export_TEMP ( R_str ) select rsWCol!r4_wcol_outstring & rsBottl!bottleoutstring;"
Case Is = "1" ' 1 bottle
' Debug.Print rsWCol!r4_wcol_outstring & rsBottl!bottleoutstring
DoCmd.RunSQL writeRecSQL
The select part of my SQL statement does not seem to be getting values.
I understand that, normally, it might be something like select fieldX from tablex
And that my statement is more like: select rs!foo
An 'Enter Parameter Value' message box is raised asking for the value of r4_wcol_outstring
(Following the SELECT in my SQL with a FROM raises VB "Run-time error '3134' syntax error in INSERT INTO statement.")
I could use some advice or an example of how write an SQL statement that will my record set parameter values.
Good place to start is Microsoft's site:
https://msdn.microsoft.com/en-us/library/bb208861(v=office.12).aspx
But if you just want to insert values from a record you just retrieved into another table
try wrapping fields in escaped double quotes and concetanting the values outside the hardcoded string.
As in:
writeRecSQL = "INSERT INTO tbl_R_export_TEMP ( [R_str] ) VALUES (""" & rsWCol!r4_wcol_outstring & rsBottl!bottleoutstring & """);"
Besides Docmd.RunSQL, you can also look at CurrentDB.Execute and predefined parameter queries using the Querydefs object

MySQL Add Column that Summarizes data from Another Column

I have a column in MySQL table which has 'messy' data stored as text like this:
**SIZE**
2
2-5
6-25
2-10
26-100
48
50
I want to create a new column "RevTextSize" that rewrites the data in this column to a pre-defined range of values.
If Size=2, then "RevTextSize"= "1-5"
If Size=2-5, then "RevTextSize"= "1-5"
If Size=6-25, then "RevTextSize"="6-25"
...
This is easy to do in Excel, SPSS and other such tools, but how can I do it in the MySQL table?
You can add a column like this:
ALTER TABLE messy_data ADD revtextsize VARCHAR(30);
To populate the column:
UPDATE messy_data
SET revtextsize
= CASE
WHEN size = '2' THEN '1-5'
WHEN size = '2-5' THEN '1-5'
WHEN size = '6-25' THEN '6-25'
ELSE size
END
This is a brute-force approach, identifying each distinct value of size and specifying a replacement.
You could use another SQL statement to help you build the CASE expression
SELECT CONCAT(' WHEN size = ''',d.size,''' THEN ''',d.size,'''') AS stmt
FROM messy_data d
GROUP BY d.size
Save the result from that into your favorite SQL text editor, and hack away at the replacement values. That would speed up the creation of the CASE expression for the statement you need to run to set the revtextsize column (the first statement).
If you want to build something "smarter", that dynamically evaluates the contents of size and makes an intelligent choice, that would be more involved. If was going to do that, I'd do it in the second statement, generating the CASE expression. I'd prefer to review that, befor I run the update statement. I prefer to have the update statement doing something that's easy to understand and easy to explain what it's doing.
Use InStr() to locate "-" in your string and use SUBSTRING(str, pos, len) to get start & End number. Then Use Between clause to build your Case clause.
Hope this will help in building your solution.
Thanks

.Net Connector for MySQL - Parameter

I have a datatable, containing two rows: id char(9), eh char(4). Both rows contains numeric values (I can't change this), for example 123456789.
The query
SELECT id,eh FROM tab WHERE id LIKE '123456789'
directly in the MySQL-client works fine, in VB.net too.
But if I use a parameter in VB.net instead of building the query-string, the query returns null rows. This is what I've done (not the complete code):
Dim com As New MySqlCommand
com.CommandText = "SELECT id,eh FROM tab WHERE id LIKE #i"
com.Parameters.Add("#i", MySqlDbType.VarChar)
com.Parameters("#i").Value = number
I think, the connector does not send the quotes of the string (maybe because there are only numbers), because if I change the first query in the MySQL-client to ... LIKE 123456789, I get null rows, too.
Do you have any hints or workarounds for me?
Try
MySqlDbType.String
As your parameter type.
Note.. I do not use MySql but a quick google came up with char as a string.
EDIT
Maybe you are missing the Apostrophes around you #i
com.CommandText = "SELECT id,eh FROM tab WHERE id LIKE '#i'"

Using IN statement in parameterized crosstab query in Access

I have a crosstab query which queries a bunch of locations and gets their measurement readings. I pivot on the measurement readings so I get a table which has all the measurements for a location/date combo on each line. This works fine for getting all the data. It also works fine for filtering on one value per field. i.e. WHERE LocationID = ? AND MeasureID = ? but what I really need is to have something like WHERE LocationID IN (?) AND MeasureID IN (?) where ? is an array (or whatever gets to job done. Is this possible?
On my forms I'm using a DAO.QueryDef object to build my recordsets. I'd like to avoid building the entire query string in VBA if possible, mostly because this particular query is pretty long and I'd rather it live in a view and not a code module. With that said I can build it all in VBA but it's just not the desired solution.
You can always use replace.
sSQL = "SELECT lots of sql WHERE LocationID IN (qqlocidqq)"
sSQLWithLoc = Replace (sSQL, "qqlocidqq", "1,2,3,4")
Dim qdf As QueryDef
'A query that exists
Set qdf= CurrentDB.QueryDefs("MyJunkQuery")
'Permanently change the sql of that query
qdf.SQL = sSQLWithLoc
Looking into this a little further, it may suit you to use Instr, like so:
SELECT Table1.LocationID
FROM Table1
WHERE InStr([#List],[LocationID])>0
Tested like so:
PARAMETERS Number_List Text(50);
TRANSFORM Count(Table1.AKey) AS CountOfAKey
SELECT Table1.AText
FROM Table1
WHERE InStr([Number_List],[ANumber])>0
GROUP BY Table1.AText
PIVOT Table1.ANumber;
Where Table1 consists of fields AKey, AText, and ANumber. Number_List is a comma separated list of numbers supplied by a parameter. Instr checks for the existence of ANumber from Table1 in the supplied parameter.
There is a problem with overlap 1,2,12, but a creative use of commas may suit:
WHERE InStr("," & [Number_List] & "," , "," & [ANumber] & ",")>0
Of course the delimiter does not have to be a comma, | is often useful.

LinQ Substring Function From the Right

Im new to linQ and I've got a problem
Question: if i have a string Example "MySTring"and I need the characters at positions 5 and 6 counting from the right of the string, ie: "ST"
here's my Query
Dim result = From everyval in AllVals
where everyval.Substring(5,2)='ST'
select everyval.Name
Now this wont return the correct values from the database because the default Consideration of positions in the Substring Function is from LEft to Right.
One Solution is maybe to reverse the String and then apply the Substring Function to it.
But how should i be doing this?
can someone tell me..???
This is a rather strange requirement, usually an IndexOf/Contains is good enough for this. However, you could try (conceptually) truncating the value and testing the end using EndsWith.
Something like this perhaps (untested and probably doesn't work):
Dim result = from everyval in AllVals where everyval.Remove(4).EndsWidth("ST")
MSDN nicely lists the string functions that can be safely translated to SQL from LINQ: http://msdn.microsoft.com/en-us/vbasic/bb688085