SSRS Distinct LookupSet Issue - vb.net

I apologize for the long post but I'm losing my mind here. I've tried looking this up but I keep getting error messages on any suggested fixes on this thread:
SSRS distinct lookupset function
I've even tried to completely recreate a similar data set in that question but keep getting issues.
This is the data set I created.
Using this in the expression box, and grouping by itemID, rackID, UseByDate
Join(LookupSet(Fields!itemId.Value & Fields!UseByDate.Value & Fields!rackId.Value
, Fields!itemId.Value & Fields!UseByDate.Value & Fields!rackId.Value
, Fields!CustomerSeqNo.Value
, "PickingList"), ",")
I get
but I would like to remove the duplicates in the LookupSet so it would just display "1".
I tried the first 2 options in that link above but they both provided an error message:
Public Shared Function RemoveDuplicates(m_Array As Object()) As String()
System.Array.Sort(m_Array)
Dim k As Integer = 0
For i As Integer = 0 To m_Array.Length - 1
If i > 0 AndAlso m_Array(i).Equals(m_Array(i - 1)) Then
Continue For
End If
m_Array(k) = m_Array(i)
k += 1
Next
Dim unique As [String]() = New [String](k - 1) {}
System.Array.Copy(m_Array, 0, unique, 0, k)
Return unique
End Function
with this expression:
=Join(Code.RemoveDuplicates(LookupSet(Fields!itemId.Value & Fields!UseByDate.Value & Fields!rackId.Value
, Fields!itemId.Value & Fields!UseByDate.Value & Fields!rackId.Value
, Fields!CustomerSeqNo.Value
, "PickingList")), ",")
returns this warning:
[rsRuntimeErrorInExpression] The Value expression for the textrun 'CustomerSeqNo.Paragraphs[0].TextRuns[0]' contains an error: Operator '&' is not defined for type 'Integer' and type 'CalculatedFieldWrapperImpl'. and this error
The other solution doesn't even deploy. Any help here?

Luckily for you #JMG, I just had to do this for a customer!
Here's the function:
public function DistinctValues(input() as Object) as string
dim newList as String
for each n as string in input
if InStr(newList, cstr(n) + ", ") = false
newList += cstr(n) + ", "
end if
next
return left(newList, len(newList) -2)
end function
So what it's doing is parsing through each value in the array. We are going to insert each unique value into a comma delimited string. Before doing so, we just check the string with InStr to see if that value already exists.
Make sure you cast the return value to string via CSTR(Fields!CustomerSeqNo.Value) to avoid any datatype issues. Your code should look something like this.
Code.DistinctValues(LookupSet(Fields!itemId.Value & Fields!UseByDate.Value & Fields!rackId.Value, Fields!itemId.Value & Fields!UseByDate.Value & Fields!rackId.Value, CSTR(Fields!CustomerSeqNo.Value), "PickingList"))

Related

MS Access VBA - Loop Split Function and Output Either First Value (If Not Null) or Last Value

I have a field in my Access database that contains values such as 24,25,152, 128,152, ,113, 113 and NULLS.
When there is only one value present in the field I would like the first value to be my output (113 for ,113 and 113) and when there is more than one value present I would like the last value to be my output (152 for 24,25,152 and 128,152).
Right now I have a user-defined function that is invoked by a query that has been hard-coded to account for the correct number of commas/values present in the field. In the future there will be more commas so I would like to account for those and I'd like my output to be in a single column (as opposed to having one column per value after each comma).
Here is VBA code for that user-defined function which came from this post.
Function mySplit(sMyText As String, sDelim As String, lIndx As Long) As String
On Error GoTo Error_Handler
mySplit = Split(sMyText, sDelim)(lIndx)
Error_Handler_Exit:
On Error Resume Next
Exit Function
Error_Handler:
If Err.Number = 9 Then
mySplit = ""
Else
MsgBox "The following error has occured" & vbCrLf & vbCrLf & _
"Error Number: " & Err.Number & vbCrLf & _
"Error Source: mySplit" & vbCrLf & _
"Error Description: " & Err.Description & _
Switch(Erl = 0, "", Erl <> 0, vbCrLf & "Line No: " & Erl) _
, vbOKOnly + vbCritical, "An Error has Occured!"
End If
Resume Error_Handler_Exit
End Function
Here is the query:
SELECT Field, mySplit([field].[table],",",0) AS 1, mySplit([field].[table],",",1) AS 2, mySplit([field].[table],",",2) AS 3, Val(IIf([3]<>"",[3],IIf([2]<>"",[2],IIf([1]<>"",[1])))) AS [Value]
FROM Table;
Ideally I'd to have a single field that looks like the "Value" field (outlined in green) in the image below.
Right now that value field is a bunch of nested if statements looking at the 1, 2, and 3 columns. I know I need to modify this code to count the delimiters and then loop through each delimiter and take either the first value (if there is only one) and the last value (if there is more than one) but I am not sure how to go about achieving that.
Any help will be greatly appreciated.
EDIT
Try this.
Just Split the value and return the last element in the array. If the value is null, return an empty string.
Public Function SplitToLast(Value As Variant) As String
On Error GoTo Trap
If IsNull(Value) Then GoTo Leave
Dim arr As Variant
arr = Split(Value, ",")
SplitToLast = arr(UBound(arr))
Leave:
On Error GoTo 0
Exit Function
Trap:
MsgBox Err.Description, vbCritical
Resume Leave
End Function
Try this:
Public Function GetLastValue(ByVal value As Variant, ByVal delimiter As String) As String
If IsNull(value) Then Exit Function
If Len(delimiter) = 0 Then
GetLastValue = value
Exit Function
End If
Dim tmpValue As String
tmpValue = Trim(CStr(value))
Do While tmpValue Like "*" & delimiter
tmpValue = Trim(Left(tmpValue, Len(tmpValue) - Len(delimiter)))
Loop
If Len(tmpValue) = 0 Then Exit Function
Dim tmpArr() As String
tmpArr = Split(tmpValue, delimiter)
GetLastValue = tmpArr(UBound(tmpArr))
End Function
It also takes care of multiple delimiters at the end of the value like 1,2,3,, ,.
It also works if the length of the delimiter is > 1.
In case value is an empty string, the result will be an empty string too.
In case delimiter is an empty string, the result will be value.
This example calling works fine:
SELECT GetLastValue([Field1],",") AS LastValue FROM Table1
If you edit the query in the query design view and not in SQL view, take care of the , which separates the parameters. There it must be a ; instead.

Using Ms Access VBA, how do I check the value of a variable to see if it has a value other than "', "

I have a variable with a string...and I want to know if it contains any value other than single quote, comma and a space ("', ") I'm using vba in excel.
for example, i have a varible strA = "'test', 'player'"
I want to check to see if strA has any characters other than "', " (single quote, comma and space).
Thanks
Here is a strategy based on Count occurrences of a character in a string
I don't have vba handy, but this should work. The idea is to remove all these characters and see if anything is left. text represents your string that is being tested.
Dim TempS As String
TempS = Replace(text, " " , "")
TempS = Replace(TempS, "," , "")
TempS = Replace(TempS, "'" , "")
and your result is Len(TempS>0)
Another approach is to use recursion by having a base case of false if the string is empty, if the first character is one of the three call ourselves on the rest of the string, or if not the value is true. Here is the code
function hasOtherChars(s As String) As Boolean
hasOtherChars=false
if (len(s)=0) then
exit function
end if
Dim asciiSpace As Integer
asciiSpace = Asc(" ")
Dim asciiComma As Integer
asciiComma= Asc(",")
Dim asciiApostrophe As Integer
asciiApostrophe = Asc("'")
Dim c as Integer
c = Asc(Mid$(s, 1, 1))
if ((c=asciiSpace) or (c=asciiComma) or (c=asciiApostrophe)) then
hasOtherChars = hasOtherChars(Mid$(s,2))
else
hasOtherChars=true
end if
End function
Again I am borrowing from the other thread.

String builder SELECT query when a variable has an apostrophe

A colleague of mine has created a program that reads a text file and assigns various values from it to variables that are used in SQL statements.
One of these variables, gsAccounts is a string variable.
Using a string builder, a SELECT statement is being built up with sql.append. At the end of the string, there is the following line:
sql.Append(" WHERE L.Account_Code IN(" & gsAccounts & ")"
The problem that I'm having is that sometimes, not always, gsAccounts (a list of account codes) may contain an account code with an apostrophe, so the query becomes
"WHERE L.Account_Code IN('test'123')"
when the account code is test'123
I have tried using double quotes to get around it in a "WHERE L.Account_Code IN("""" & gsAccounts & """")" way (using 4 and 6 " next to each other, but neither worked)
How can I get around this? The account_Code is the Primary Key in the table, so I can't just remove it as there are years worth of transactions and data connected to it.
I posted the following example here 10 years ago, almost to the day. (Oops! thought it was Jun 5 but it was Jan 5. 10.5 years then.)
Dim connection As New SqlConnection("connection string here")
Dim command As New SqlCommand
Dim query As New StringBuilder("SELECT * FROM MyTable")
Select Case Me.ListBox1.SelectedItems.Count
Case 1
'Only one item is selected so we only need one parameter.
query.Append(" WHERE MyColumn = #MyColumn")
command.Parameters.AddWithValue("#MyColumn", Me.ListBox1.SelectedItem)
Case Is > 1
'Multiple items are selected so include a parameter for each.
query.Append(" WHERE MyColumn IN (")
Dim paramName As String
For index As Integer = 0 To Me.ListBox1.SelectedItems.Count - 1 Step 1
'Name all parameters for the column with a numeric suffix.
paramName = "#MyColumn" & index
'Add a comma before all but the first value.
If index > 0 Then
query.Append(", ")
End If
'Append the placeholder to the SQL and add the parameter to the command
query.Append(paramName)
command.Parameters.AddWithValue(paramName, Me.ListBox1.SelectedItems(index))
Next index
query.Append(")")
End Select
command.CommandText = query.ToString()
command.Connection = connection
Single quotes can be "escaped" by making them double single quotes. E.g. ' becomes ''.
However this approach is generally not recommended due to the high risk of SQL injection - a very dangerous and prevalent issues. See: https://www.owasp.org/index.php/SQL_Injection
To avoid this most libraries will include some type of escaping mechanism including the use of things like prepared statements in the Java world. In the .net world this may be of use: https://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlcommand.prepare(v=vs.110).aspx
If you only have one with a field, this is the easiest solution
Private Function gsAccountsConvert(ByVal gsAccounts As String)
Dim gsAccountsString As String = ""
Dim StringTemp
StringTemp = gsAccounts.Split(",")
Dim i As Integer
For i = 0 To UBound(StringTemp)
StringTemp(i) = StringTemp(i).ToString.Trim
If StringTemp(i) <> "" Then
If StringTemp(i).ToString.Substring(0, 1) = "'" Then
StringTemp(i) = """" & StringTemp(i).ToString.Substring(1, Len(StringTemp(i).ToString) - 2) & """"
End If
End If
If i <> UBound(StringTemp) Then
gsAccountsString = gsAccountsString & StringTemp(i).ToString.Replace("'", "''") & ","
Else
gsAccountsString = gsAccountsString & StringTemp(i).ToString.Replace("'", "''") & ""
End If
Next
gsAccountsString = gsAccountsString.Replace("""", "'")
Return gsAccountsString
End Function

Visual Studio - CDbl to Double.TryParse when inputting to array

I'm finishing up a project and needed some clarification on a particular issue I'm running into.
Do While intCount < dblNumbers.Length AndAlso strInput <> String.Empty
dblNumbers(intCount) = CDbl(InputBox("Please enter number " & (intCount + 1) & "."))
intCount += 1
Loop
I'm running into issues changing that a to Double.TryParse for validating as opposed to the CDbl. Any of the ways I've entered it have caused the inputs to not store in the array. Thanks in advance.
TryParse doesn't return the converted value. It returns the validation result. You get the converted value from the parameter.
Dim number As Double
If Double.TryParse(InputBox("Please enter number " & (intCount + 1) & "."), number) Then
dblNumbers(intCount) = number
Else
'Invalid input.
End If

Insert number of record based on checkboxlist selected value in vb.net

I have this skill checkboxlist which contains skills that can be selected by the user. If the user select two skills,two records will be inserted to the table.
I tried this one:
Dim varSkillID As Integer()
varSkillID = split(skills, ",")
If varSkillID(0).value > 0 Then
Dim sql As String = Nothing
For I = 0 To varSkillID()
sql = "INSERT INTO tblConstituentSkills (skillID) VALUES ( " & varSkillID.Value & ")"
Next I
end if
but its not working. Thanks!
I also tried this code.
Dim varSkillID() As String = Split(skillID, ",")
For i As Integer = 0 To varSkillID.Length - 1
If varSkillID(i) <> "" Then
Using sql As New SqlProcedure("spInsertSkill")
sql.AddParameter("#ConstituentIdNo", constituentIdNo)
sql.AddParameter("#skillID", varSkillID(i))
sql.ExecuteNonQuery()
End Using
End If
Next i
It works when I only select single skill. But if I select two or more skills this error appears "Nullable object must have a value."
please use the editor help to design your request. It is very hard to read.
What does the errormessage say?
There is an End If missing
Where does constituentIdNo.Value is coming from?
To call the Sub:
Call r101("123456", "1,2,3,4")
the Sub:
Public Sub r101(ByVal constituentIdNo As String, ByVal skills As String)
Dim varSkillID() As String = Split(skills, ",")
Dim sql As String = Nothing
For i As Integer = 0 To varSkillID.Length - 1
If varSkillID(i) <> "" Then sql = "INSERT INTO tblConstituentSkills (ConstituentIdNo, skillID) VALUES (" & constituentIdNo & ", " & varSkillID(i) & ")"
Next i
End Sub
This is not the cleanest code, but the best I could create from your given feedback.
I don't see why to convert skills to integer.
I just read this and saved me.separate comma separated values and store in table in sql server
Thanks stackoverflow!you're a savior!