Placing a Query Result in A String Variable - vba

Was wondering how can we put an SQL statement in a String Variable?
Example:
Dim sqlQuery as String, qHolder as String
sqlQuery = "SELECT ID.table from table WHERE ID ='" userInputTextBox "'"
Whenever i do the above statement using either OpernRecordset() or RecordSource it gives me a bug. Can you give an example on how we do this, so we can use the value of sqlQuery for comparison for example
if(sqlQuery = userInputTextBox)then
MSgBox(" Match Found " )
Else
MsgBox("No Match Found")
Big Thanks in Advance.

Use the string concatenation operator (&).
sqlQuery = "SELECT ID.table from table WHERE ID ='" & userInputTextBox & "'"
Otherwise, it's a syntax error.
UPDATE
To get the value of ID.table into a string, use the Fields property of the Recordset:
Dim s As String
' by index
s = MyRec.Fields(0)
' or by name
s = MyRec.Fields("ID.table")

Related

MS Access Query to show Inventory Counts per Person (Using comma delimited)

I'm attempting to setup a query that will show how many of each ship is owned and who owns it displaying each "Call Sign" who owns the ship in comma delimited format.
The table being used for the query is called "Members" and I'm using a Count function on the "Current Ships Owned" field in the query to get count totals.
The Base query is the following:
I used VBA to build the following module:
Public Function QueryFieldAsSeparatedString(ByVal fieldName As String, _
ByVal tableOrQueryName As String, _
Optional ByVal criteria As String = "", _
Optional ByVal sortBy As String = "", _
Optional ByVal delimiter As String = ", " _
) As String
Dim db As DAO.Database
Dim rs As DAO.Recordset
Dim sql As String
Dim whereCondition As String
Dim sortExpression As String
Dim retVal As String
Set db = CurrentDb
If Len(criteria) > 0 Then
whereCondition = " WHERE " & criteria
End If
If Len(sortBy) > 0 Then
sortExpression = " ORDER BY " & sortBy
End If
sql = "SELECT " & fieldName & " FROM " & "Members" & whereCondition & sortExpression
Set rs = db.OpenRecordset(sql, dbOpenForwardOnly, dbReadOnly)
Do Until rs.EOF
If Not IsNull(rs.Fields(0).Value) Then
retVal = retVal & Nz(rs.Fields(0).Value, "") & delimiter
End If
rs.MoveNext
Loop
retVal = Left(retVal, Len(retVal) - Len(delimiter))
QueryFieldAsSeparatedString = retVal
rs.Close
Set rs = Nothing
Set db = Nothing
End Function
I then added the field with the owners by adding the following expression to my query:
Owners: QueryFieldAsSeparatedString("[Call Sign]","Members",Count([Members]![Current Ships Owned])>=1)
But it comes back with the error "Your query does not include the specified expression 'Owners' as part of an aggregate function". Changing it from expression to group by gives an error "reserved error (-3087);"
If I remove the Count from the expression it runs but gives me all members rather than the members that own the ships.
Any help or push in the right direction would be greatly appreciated. I'm not sure what I'm missing but I think some fresh eyes on the issue may help.
Thank you!!
-Deke
Note that you have basically replicated http://allenbrowne.com/func-concat.html
The criteria parameter is the problem. It expects a string, but you pass an expression.
And even if Access silently converts it, WHERE Count([field]) >= 1 is not valid in the WHERE clause, that would only work in a HAVING clause.
But what you actually need there is a criterium that collects all Members records that belong to the current query record.
See the usage example on Allen Browne's page, and the documentation of the strWhere parameter.

SQL query, field name paseed by reference vb.net

I'm having problems trying to make this work, I have this query on an application that Im writing in vb.net 2012:
Dim strSql As String = " SELECT * FROM Table_Master WHERE field & "'= ('" & txtCadena.Text & "')"
What I need is to have the option to choose the field that I'm querying writing the field name on a textbox.
Maybe something like:
strSql As String = string.format("SELECT * FROM Table_Master WHERE [{0}] = '{1}'", txtField.text, txtFieldValue.text.replace("'","''"))
This should work (only for text, not dates, numbers etc) but you have to know that it is not the best practice.
I finally made it doing this.
Dim Query As String
Dimm DT As DataTable = New DataTable
Query = "select Actual, Description, Unit_of_measurement from Table_ARTIClES WHERE NUMPART = '" & txtPartNum.Text & "'"
Dim Table As SqlDataAdapter = New SqlDataAdapter(Query, conn)
Table.Fill(DT)
lblInventory.Text = DT.Rows(0)("Actual").ToString

Receiving an error when attempting to update a record

In my program I have a function titled runSQL, here it is:
Dim Connection As New OleDb.OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=TrainingLog.accdb")
Dim DT As New DataTable
Dim DataAdapter As OleDb.OleDbDataAdapter
Connection.Open()
DataAdapter = New OleDb.OleDbDataAdapter(query, Connection)
DT.Clear()
DataAdapter.Fill(DT)
Connection.Close()
Return DT
And I'm trying to update a record in a database using the update string, sourced from this code:
Dim sqlString As String
sqlString = "UPDATE UserRecords set FirstName = '" & txtName.Text
sqlString = sqlString & "', LastName = '" & txtSurname.Text
If ChkSmoker.Checked = True Then
sqlString = sqlString & "', Smoker = true"
ElseIf ChkSmoker.Checked = False Then
sqlString = sqlString & "', Smoker = false"
End If
sqlString = sqlString & ", Weight = " & txtWeight.Text
If RdoMale.Checked = True Then
sqlString = sqlString & ", Gender = 'm'"
ElseIf RdoFemale.Checked = True Then
sqlString = sqlString & ", Gender = 'f'"
End If
sqlString = sqlString & " WHERE UserName = '" & LstUsers.SelectedItem.ToString & "'"
runSQL(sqlString)
However once I click the save button, I get an error from line 7 of the runSQL function (not including empty line, so that's the DataAdapter.Fill(DT) line) which says "No value given for one or more required parameters."
I wondered if anyone knew why this is or how to fix it.
One thing I did think of is that, in the table being updated, there are fields other than those being mentioned in my UPDATE statement. For example there is a Yes/no field titled "TeamMember", which I don't mention in the update statement.
When using the update function, do I have to give values for every field, even those not being changed?
Thanks for reading, and hopefully helping!
You should never composea SQL query yourself. It much easies and safer (to vaoid SQL injection) to create a parameterized query, or use an stored procedure. And then execute it by pasing the query or stored procedure name and the parameter values.
Besides, in this way, you don't have to take care of what the right format is for a particular value. For example, how do you format a date? And, how do you format a boolean value? Most probably the problem with your query is the false or true value that you're trying to set for the Smoker column, because in TSQL that's a bit value, and can only be 0 or 1.
Check this to see samples of using parameters: ADO.NET Code Examples (Click the VB tab to see it in VB). You'll see that you define a parameter specifying a name with an # prefix in the query, and then you simply pass a value for each parameter in the query, and it will be passed to the server in the correct format without you taking care of it.
Taken from one of the samples:
Dim queryString As String = _
"SELECT ProductID, UnitPrice, ProductName from dbo.Products " _
& "WHERE UnitPrice > #pricePoint " _
& "ORDER BY UnitPrice DESC;"
Dim command As New SqlCommand(queryString, connection)
command.Parameters.AddWithValue("#pricePoint", paramValue)
'' command.ExecuteXXX
NOTE that you can execute the command in different ways, depending on your need to simply execute it or get an scalar value or a full dataset as a result.

SQLite SELECT from VB.Net application (Win32)

I am trying to get a result from SQL database and keep it as a variable. But with my code (see below) it returns 0 (zero). Any ideas of what am i doing wrong?
Thanks
Function getName(name As String)
Dim SQLconnect As New SQLite.SQLiteConnection()
Dim SQLcommand As SQLite.SQLiteCommand
SQLconnect.ConnectionString = "Data Source=C:\tools\names.sqlite;"
SQLconnect.Open()
SQLcommand = SQLconnect.CreateCommand
SQLcommand.CommandText = "SELECT * FROM names WHERE name = " & name & " LIMIT 1;"
Dim sqlResponse As String = SQLcommand.ExecuteNonQuery()
End Function
EDIT: I am using "return sqlResponse" for return
First thing, the sql should be(I think):
SQLcommand.CommandText = "SELECT * FROM names WHERE name = '" & name & "' LIMIT 1;"
I am not sure how text is represented in SQLite but you need some kind of delimiter like a single quote in SQL Server.
Second thing, use paramterized query to stop yourself from being hijacked by SQL Injections
Third, a SELECT uses a ExecuteReader, and in case where you want only one item, try ExecuteScalar. ExecuteNonQuery is for insert, update delete.
ExecuteNonQuery does not return a value so therefore it will always be 0. You need to use
Dim sqlResponse As String = SQLcommand.ExecuteScalar()

Update in new column after inserting into 2 columns in a db

I am using following code to insert records into a table from another table....
Private Sub InsDuplicateDB()
Dim strInsDup As String = "INSERT INTO Duplicate_srno(Sr_no,chalan_no) SELECT sr_no,chaln_no FROM Vendor_Machine where sr_no=#srno"
Dim comm_InsDup As OleDb.OleDbCommand = New OleDb.OleDbCommand(strInsDup, cnnOLEDB)
comm_InsDup.Parameters.AddWithValue("#srno", cmbSn_no.Text)
comm_InsDup.ExecuteNonQuery()
Dim strUpdDup As String = "UPDATE Duplicate_srno SET sr_no = #srno,chaln_no =#chn_no,Problem=#problemWHERE sr_no = #srno AND chalan_no=#chn_no"
Dim comm_Update As OleDb.OleDbCommand = New OleDb.OleDbCommand(strUpdDup, cnnOLEDB)
comm_Update.Parameters.AddWithValue("#srno", cmbSn_no.Text)
comm_Update.Parameters.AddWithValue("#chn_no", cmbChal_no.Text)
comm_Update.Parameters.AddWithValue("#problem",strProb)
comm_Update.ExecuteNonQuery()
End Sub
Here strProb is a string whose value is assigned in anoter sub function..
Here it gives error as "No values given for one or more required parameter.."
Please resolve my problem
I don't know if this is a typo or not, but the update string lacks of a space between the parameter name #problem and the WHERE clause
Dim strUpdDup As String = "UPDATE Duplicate_srno SET sr_no = #srno,chaln_no =#chn_no," & _
"Problem=#problem WHERE sr_no = #srno AND chalan_no=#chn_no"
^
However the update string could be simplified because you are updating two fields with the same values used in the where clause
Dim strUpdDup As String = "UPDATE Duplicate_srno SET Problem=#problem " & _
"WHERE sr_no = #srno AND chalan_no=#chn_no"
Apart from the missing space the error message says that the engine expects more parameters.
In OleDb the parameters are not recognized by their name. You need the same number of parameter that are defined by the placeholders in the string. In your original text, you have 5 placeholders but you add only 3 parameters. It doesn't matter if two of them are the same.
The revised code coould be the following
Dim strUpdDup As String = "UPDATE Duplicate_srno SET Problem=#problem " & _
"WHERE sr_no = #srno AND chalan_no=#chn_no"
Dim comm_Update As OleDb.OleDbCommand = New OleDb.OleDbCommand(strUpdDup, cnnOLEDB)
comm_Update.Parameters.AddWithValue("#problem",strProb)
comm_Update.Parameters.AddWithValue("#srno", cmbSn_no.Text)
comm_Update.Parameters.AddWithValue("#chn_no", cmbChal_no.Text)
Notice how I have added the #problem parameter as first in the collection. Now, the parameter collection is in the same order in which the placeholders are present in the command text.