Get SQL single value from query as String - sql

I have the following code in my code behind:
Dim name As String
name.text= Staff.LoadName(StaffID)
The following query in my Class:
Public Function LoadName(ByVal ID As String)
Dim ds As New DataSet
Dim SQL As String = ""
SQL="select name from Staff where StaffID='" & ID & "' "
ds = Common.QueryDataByDataset(SQL)
ds.Tostring()
Return ds
End Function
But the name.Text doesn't show the value. How to I get the single value and convert it to string to display? Thanks

I am guessing the Common.QueryDataByDataset is from your library or some third party. Assuming it is executing the query and populating the dataset, you should be able to change the last two lines of the LoadName function to this:
String name = ds.Tables.Item("Staff").Rows(0)("name").ToString()
return name
You should add error handling in this method. For example, check to make sure the query returns exactly one result. Also, this method appears to be susceptible to SQL injection: http://en.wikipedia.org/wiki/SQL_injection

Related

Access VBA Run-time error 3078, or Type Mismatch on DCount function

Objective: I'm building VBA code to filter through an address table SunstarAccountsInWebir_SarahTest. I want to loop through first and see if the address is "valid".
If it is not valid – export to different table.
If it is valid – it enters another nested if/then within "valid" address rows:
If their ID, external_nmad_id matches the ID of the second table 1042s_FinalOutput_7, I want to update one of the columns in the second table box13c_Address.
If it doesn't match an ID of the second table – it will be exported to a different table.
My problem is when I run my code it is returning
Run-Time error 3078: cannot find table or query
(it's breaking at the line where I compare the value of the cell (as string) against the DCount of table 2). If I remove the quotes around it I get a different error:
Type mismatch against the DCount
I feel like I'm missing something simple but can't tell what. How can I get my code to match a string value called in !external_nmad_id against the rest of the table called in my string? DCount("[ID]", StrSQL1)
Public Sub EditFinalOutput2()
'set variables
Dim i As Long
Dim qs As DAO.Recordset
Dim ss As DAO.Recordset
Dim StrSQL1 As DAO.Recordset
Dim IRSfileFormatKey As String
Dim external_nmad_id As String
Dim nmad_address_1 As String
Dim nmad_address_2 As String
Dim nmad_address_3 As String
Dim mytestwrite As String
'open reference set
Set db = CurrentDb
Set qs = db.OpenRecordset("SunstarAccountsInWebir_SarahTest")
'Set ss = db.OpenRecordset("1042s_FinalOutput_7")
'Set StrSQL1 = db.OpenRecordset("SELECT RIGHT(IRSfileFormatKey, 10) As ID
'FROM 1042s_FinalOutput_7;")
With qs.Fields
intCount = qs.RecordCount - 1
For i = 0 To intCount
If (IsNull(!nmad_address_1) Or (!nmad_address_1 = !nmad_city) Or (!nmad_address_1 = !Webir_Country) And IsNull(!nmad_address_2) Or (!nmad_address_2 = !nmad_city) Or (!nmad_address_2 = !Webir_Country) And IsNull(!nmad_address_3) Or (!nmad_address_3 = !nmad_city) Or (!nmad_address_3 = !Webir_Country)) Then
DoCmd.RunSQL "INSERT INTO Addresses_ToBeReviewed SELECT SunstarAccountsInWebir_SarahTest.* FROM SunstarAccountsInWebir_SarahTest WHERE (((SunstarAccountsInWebir_SarahTest.external_nmad_id)='" & qs!external_nmad_id & "'));"
Else:
Set ss = db.OpenRecordset("1042s_FinalOutput_7")
Set StrSQL1 = db.OpenRecordset("SELECT RIGHT(IRSfileFormatKey, 10) As ID FROM 1042s_FinalOutput_7;")
If !external_nmad_id = DCount("[ID]", StrSQL1) Then
ss.Edit
ss.Fields("box13c_Address") = qs.Fields("nmad_address_1") & qs.Fields("nmad_address_2") & qs.Fields("nmad_address_3")
ss.Update
Else: DoCmd.SetWarnings False
DoCmd.RunSQL "INSERT INTO Addresses_NotUsed SELECT SunstarAccountsInWebir_SarahTest.* FROM SunstarAccountsInWebir_SarahTest WHERE (((SunstarAccountsInWebir_SarahTest.external_nmad_id)='" & qs!external_nmad_id & "'));"
DoCmd.SetWarnings True
End If
End If
qs.MoveNext
Next i
End With
'close reference set
qs.Close
Set qs = Nothing
ss.Close
Set ss = Nothing
End Sub
The issue is that the DCount function cannot operate directly against a Recordset.
You are declaring StrSQL1 as a RecordSet object and setting it to a RecordSet based on your Select statement.
Set StrSQL1 = db.OpenRecordset("SELECT RIGHT(IRSfileFormatKey, 10) As ID FROM 1042s_FinalOutput_7;")
You are then trying to pass this RecordSet to the DCount function which cannot accept a RecordSet object as the Domain parameter. As you can see in MSDN the DCount function requires a String parameter in the second position to define the "query" that you wish to "Count". Hence the 3078 error. When you remove the quotes around [ID] in your DCount line, you get Type Mismatch as a compile error because [ID] is not a String or String variable.
After you resolve that, you might want to reconsider your If statement. You haven't provided a sample of what kind of value !external_nmad_id will contain, other than the fact that it is a String value. The DCount function is going to return the number of rows found in the Domain (query) that you told it to count, so it appears you will be comparing a string (which may possibly contain alpha characters) to a number. Access will implicitly convert the DCount numeric result to a String for the sake of the comparison, but if your !external_nmad_id String is truly 10 characters or contains alpha characters, they will never match.
You cannot use a VBA recordset inside a domain aggregate like DCount as a string literal is required for table/query name argument. Simply save your query and then reference it by name in DCount.
SQL (save as query)
SELECT RIGHT(IRSfileFormatKey, 10) As ID FROM 1042s_FinalOutput_7;
VBA
If !external_nmad_id = DCount("[ID]", "mySavedQuery") Then
...
End If

Multi-value parameter using AND logic instead of OR

My report uses a multi-value parameter string to search through a block of text. We want the ability to only return results that meet all the values entered for this string. For example: Only return rows that have "Biopsy", "Prostate", AND "Lateral" values.
How can I accomplish this?
I'm not sure if crystal report accepts that condition (REGEXP_LIKE). Btw... You have to send the parameters one by one, for example:
Dim p As New Report
p.parameter1 = txtParameter1.Text
p.parameter2 = txtParameter2.Text
p.parameter3 = txtParameter3.Text
p.show()
Then in report
Public parameter1 As String
Public parameter2 As String
Public parameter3 As String
If String.IsNullOrWhiteSpace(parameter1) Then
"report-object".SetParameterValue("Parameter in Query", "'%'")
Else
"report-object".SetParameterValue("Parameter in Query", "'" + parameter1 + "%'")
End If
.
.
I usually use this code for that.. and well in your command object, you only need a simple AND to match the parameters.

FillDataSet is not declared msg

Public Function GetCategories() As DataSet
Dim query As String = "SELECT * FROM Categories"
Dim cmd As New OleDbCommand(query)
Return FillDataSet(cmd, "Categories")
End Function
Presumably, you haven't actually defined the FillDataSet method.
I think you may have meant to use the SqlDataAdapter's Fill method. You can see a complete example of how to do that here: Direct method from SQL command text to DataSet

how to set result of aggregate sql query as lable caption

I am using this code to retrieve no of machines (count)...
Dim strCntSr As String = "SELECT count(sr_no) FROM Vendor_Machine WHERE chaln_no='" & cmbChal_no.Text & "'"
comm_getCnt = New OleDb.OleDbCommand(strCntSr, cnnOLEDB)
comm_getCnt.ExecuteNonQuery()
***Here I want to set result of the above query [count(sr_no)] as text of lblMachine***
lblMachine.Text =
Please suggest me the code.. Thank you..
ExecuteNonQuery return only the number of the rows affected not the value/s returned by the query.
In your case the correct method to use is ExecuteScalar that returns the first column of the first row obtained by the query.
Notice also that is a very bad practice to build query text using string concatenation.
The problems are Sql Injection and correct parsing of text provided by you.
Dim strCntSr As String = "SELECT count(sr_no) FROM Vendor_Machine WHERE chaln_no=?"
comm_getCnt = New OleDb.OleDbCommand(strCntSr, cnnOLEDB)
comm_getCnt.Parameters.AddWithValue("#p1", cmbChal_no.Text)
Dim result = comm_getCnt.ExecuteScalar()
lblMachine.Text = Convert.ToInt32(result);

How can I get the URL and Querystring? vb.net

I am refactoring some legacy code. The app was not using querystrings. The previous developer was hard coding some variables that the app uses in other places.
Like this using VB.NET
so.Cpage = "ContractChange.aspx"
My question is can I programatically set this value and include the current querystring?
I want so.Cpage to be something like ContractChange.aspx?d=1&b=2
Can I do this with the request object or something? Note, I don't need the domain.
To get the current query string you would simply do something like the following:
Dim query as String = Request.QueryString("d")
This will assign the value of the "d" querystring to the string variable "query". Note that all query string values are strings, so if you're passing numbers around, you'll need to "cast" or convert those string values to numerics (be careful of exceptions when casting, though). For example:
Dim query as String = Request.QueryString("d")
Dim iquery as Integer = CType(query, Integer)
The QueryString property of the Request object is a collection of name/value key pairs. Specifically, it's of type System.Collections.Specialized.NameValueCollection, and you can iterate through each of the name/value pairs as so:
Dim coll As System.Collections.Specialized.NameValueCollection = Request.QueryString
Dim value As String
For Each key As String In coll.AllKeys
value = coll(key)
Next
Using either of these mechanisms (or something very similar) should enable you to construct a string variable which contains the full url (page and querystrings) that you wish to navigate to.
Try this:
so.Cpage = "ContractChange.aspx?" & Request.RawUrl.Split("?")(1)
In VB.Net you can do it with the following.
Dim id As String = Request.Params("RequestId")
If you want to process this in as an integer, you can do the following:
Dim id As Integer
If Integer.TryParse(Request.Params("RequestId"), id) Then
DoProcessingStuff()
End If
try this
Dim name As String = System.IO.Path.GetFileName(Request.ServerVariables("SCRIPT_NAME"))
Dim qrystring As String = Request.ServerVariables("QUERY_STRING")
Dim fullname As String = name & "/" & qrystring
Not sure about the syntax in VB.NET but in C# you would just need to do
StringId = Request.QueryString.Get("d");
Hope this helps.