Strange issue with query design function in access - sql

I have the error message "Data type mismatch in criteria expression" in a query I am making using query builder in access. The problem is caused by a function inside the query.
This is the function :
Function Sudent_Selected_Next_Active_Season(Code_Student, Starting_Date As Date, Code_Project) As Boolean
Dim MyReturn
Dim SQLDate
SQLDate = Format$(Starting_Date, "\#mm\/dd\/yyyy\#")
MyReturn = DCount("[code_student]", "Project_Termination_level_2", "[Code_Student]=" & Code_Student & " and [ending] > " & SQLDate & " and [code_project] <>" & Code_Project)
If IsNull(MyReturn) Then
MyReturn = 0
End If
If MyReturn > 0 Then
Sudent_Selected_Next_Active_Season = True
Else
Sudent_Selected_Next_Active_Season = False
End If
End Function
I tried as criteria 0, -1, "0", "-1", True, False and they all give the same error.
If I remove the criteria and I review the data, all the row are composed of -1 and 0
This is the SQL used.
SELECT Sudent_Selected_Next_Active_Season([t_student].[code_student],[T_Project].[starting_date],[T_project].[code_project]) AS ActiveNextSeason
FROM (T_Project INNER JOIN T_Project_Student ON T_Project.Code_Project = T_Project_Student.Code_Project) INNER JOIN T_Student ON T_Project_Student.Code_Student = T_Student.Code_Student
WHERE (((Sudent_Selected_Next_Active_Season([t_student].[code_student],[T_Project].[starting_date],[T_project].[code_project]))=-1)) OR (((Sudent_Selected_Next_Active_Season([t_student].[code_student],[T_Project].[starting_date],[T_project].[code_project]))=-1));
If anyone could give me an idea of where to search for a solution I would appreciate it. If anyone wants more information please just ask.

not sure why you have the same condition twice in your WHERE clause, but in general, with those errors, you need to convert the data type on one side to match the other.
You could change the return value of your function to integer, cast the boolean return value to integer, or cast the -1 as boolean.
If you've changed the return value of the function to an integer, then the comparison with -1 should not give you a data type conversion error. Try this:
SELECT
s.code_student,p.starting_date,p.code_project,
Sudent_Selected_Next_Active_Season(s.code_student,p.starting_date,p.code_project) AS ActiveNextSeason
FROM
T_Project p INNER JOIN
T_Project_Student ps ON
p.Code_Project = ps.Code_Project INNER JOIN
T_Student s ON
ps.Code_Student = s.Code_Student
WHERE
Sudent_Selected_Next_Active_Season(s.code_student,p.starting_date,p.code_project)=-1

Related

SSRS Distinct LookupSet Issue

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"))

Managing Blank field from Linq Query

I am writing a method in VB.Net that runs a LINQ query on my database, and puts the information from the query into textboxes on a form.
Public Sub OpenPartWindow(ByVal partNumber As String)
Using dbContext As New DB_LINQDataContext
Dim query = (From p In dbContext.Parts
Join ppl In dbContext.Part_Price_Logs On p.Part_ID Equals ppl.Part_ID
Where p.Part_Number = partNumber
Select p.Part_Number, p.Part_Description, p.Part_Information, p.Supplier.Supplier_Name, _
p.Part_Manufacturer.Manufacturer_Name, p.Part_Subcategory.Part_Category.Category_Description, _
p.Part_Subcategory.Subcategory_Description, ppl.Cost_Per_Unit, ppl.Discount_Percentage).First()
MessageBox.Show(query.ToString())
txtPartNum.Text = query.Part_Number.ToString()
txtSupplier.Text = query.Supplier_Name.ToString()
txtManufacturer.Text = query.Manufacturer_Name.ToString()
txtPrice.Text = query.Cost_Per_Unit.ToString()
txtDiscount.Text = query.Discount_Percentage.ToString()
txtDescription.Text = query.Part_Description.ToString()
txtInfo.Text = query.Part_Information.ToString()
Me.Show()
End Using
End Sub
The issue I am having right now is with the last field, the txtInfo TextBox. You see the Part_Information field on the database allows NULL values. So when I go to fill the field when the field is null I am getting a NullReferenceException, which is understandable. However I cannot find a way to get around this exception.
I've tried:
If Not IsNothing(query._Part_Information.ToString()) Then
As well as
If query.Part_Information.Length > 0 Then
As If statements to run through first. But I keep getting the error each time. So I am confused on how I am suppose to deal with this error.
You can use either of the following options:
txtInfo.Text = String.Format("{0}", query.Part_Information)
txtInfo.Text = $"{query.Part_Information}" → $ - String Interpolation
txtInfo.Text = query.Part_Information?.ToString() → ?. - Null Conditional Operator
If query.Part_Information is null, the first two expressions result in Sting.Empty and the last one result in Nothing.

Variant Join in MS Access

I am converting a spreadsheet that had over 80 Sumifs for output.
For a query, I can join 2 tables, but they depend on 6-8 factors that aren't consistent, hence, the sumifs.
I've been successful with right joins in some instances, but most of the time I have to piece meal all of the conditions.
One of my approaches is to write a function like this:
Public Function DetermineCOB_ID(strFund As String, strType As String, strMDEP As String, _
strTier1 As String, strAirGround As Variant, strAcctType As String) As Integer
If strFund = "A82AB" And strType = "Base" And strTier1 = "2 BCT" And strMDEP = "W25D" And strAcctType = "Subordinate_Cmds" Then
DetermineCOB_ID = 1
ElseIf strFund = "A82AC" And strType = "Base" And strMDEP = "W25D" And strAcctType = "Subordinate_Cmds" Then
DetermineCOB_ID = 2
ElseIf strFund = "A82AD" And strType = "Base" And strMDEP = "W25D" And strAirGround = "Ground" And strAcctType = "Subordinate_Cmds" Then
DetermineCOB_ID = 3
Else
DetermineCOB_ID = 0
End If
End Function
But I will have to write 80 separate ElseIf statements.
I'd like to hook up my logic to a control table that the user can change the factors that determine the values.
This would somehow involve a 'variant' join everywhere there is a join where one is not required. I hope I am making sense.
Is there another approach to solving this problem?
Yes, I am working with a back end that leaves a lot to be desired. In the interim, I'm probing for alternate solutions. Do you know a way to make a join respond like a variant variable i.e so it can work with null values. I've tried outer joins but it doesn't really work.

Linq Dynamic Error with Dynamic Where clause

I have a four dropdownlists that are used to filter/order a gridview.
If any of the first 3 dropdowns have a selected value other than 0 the the WhereFlag is set to True. The fourth dropdown is used to dictate which column the grid is ordered by.
My code for databinding the gridview uses System.Linq.Dynamic and is shown below...
Dim dc As New DiaryDataContext
If WhereFlag = False Then
'This section works...
Dim AList = dc.D_AreaSubAreas _
.OrderBy(ddl_SortBy.SelectedValue)
Dim dl As List(Of D_AreaSubArea)
dl = AList.ToList
dl.Insert(0, New D_AreaSubArea With {.Ref = 0,
.Area = "",
.SubArea = "",
.Allocation = "Allocation...",
.Redundant = False})
gv_AreaSubArea.DataSource = dl
gv_AreaSubArea.DataBind()
'Gridview successfully binds
'If ddl_SortBy value is changed... Gridview binds OK.
Else
'This section gives error...
Dim WhereBuild As New StringBuilder
If ddl_AreaFilter.SelectedIndex <> 0 Then
WhereBuild.Append("Area = '" & ddl_AreaFilter.SelectedValue & "'")
AndFlag = True
End If
If ddl_SubAreaFilter.SelectedIndex <> 0 Then
If AndFlag = True Then
WhereBuild.Append(" AND ")
End If
WhereBuild.Append("SubArea = '" & ddl_SubAreaFilter.SelectedValue & "'")
AndFlag = True
End If
If ddl_AllocFilter.SelectedIndex <> 0 Then
If AndFlag = True Then
WhereBuild.Append(" AND ")
End If
WhereBuild.Append("Allocation = '" & ddl_AllocFilter.SelectedValue & "'")
End If
'ERROR HERE
Dim AList = dc.D_AreaSubAreas _
.Where(WhereBuild.ToString) _
.OrderBy(ddl_SortBy.SelectedValue)
'END ERROR
Dim dl As List(Of D_AreaSubArea)
dl = AList.ToList
dl.Insert(0, New D_AreaSubArea With {.Ref = 0,
.Area = "",
.SubArea = "",
.Allocation = "Allocation...",
.Redundant = False})
gv_AreaSubArea.DataSource = dl
gv_AreaSubArea.DataBind()
End If
The error I get is with the dynamic where clause. The error I get is
ParseException is unhandled by user code. Character Literal must contain exactly one character
It points to the query AList in the Else fork. The only difference between it and the query in the If fork is the addition of the Where clause... but I have been unable to deduce what is wrong with my code. AHA.
The error points to the place where the LINQ query is evaluated and, as the message says, the problem is that a character is expected but several characters were provided.
Check whenever ddl_AreaFilter.SelectedValue, ddl_SubAreaFilter.SelectedValue or ddl_AllocFilter.SelectedValue actually contain a character or a string. If they contain more than one character, you should replace ' with \" when building the where condition, for instance:
WhereBuild.Append("Area = """ & ddl_AreaFilter.SelectedValue & """")
EDIT
You must make sure that the type of the value contained in each SelectedValue string match the corresponding database type. For instance, if the database column is a numeric type, the string content will be casted to a numeric type.
When you specify the value in the comparison using quotes, you are indicating that the type on the right side of the comparison is either character or string (depending on whenever you use single or double quotes, respectively).
So, what are the Area, SubArea and Allocation types in the database?
Single character: the value in your query should be around single quotes: Area = 'value'
Strings (for instance, varchar):you must use double quotes: Area = "value"
Other: then you should use no quotes: Area = value

LINQ Join between datatables, two untyped fields

I'm querying two databases and trying to join the result sets and query out of them using LINQ. It seems it would be an easy task, but without doing an explicit join I'm having major performance issues. When I do the explicit join, I am having trouble with VB syntax for making things explicit types. Working Code, Cleaned:
For Each CurrRow In ResultsA.Tables(15).Rows
CurrDate = CurrRow("Date")
CurrID = CurrRow("ID")
CurrVal = CurrRow("Val")
Dim ResultsB = From SMW In DataSetA.Tables(0).AsEnumerable() _
Where SMW("ID") = CurrScheduleID And SMW("Time") = CurrProfileDate _
Select UTC_TS = SMW("Time"), Value = (SMW("VALUE") / 1000), Time_Zone = SMW("Time_Zone"), ID = SMW("ID")
Dim CurrentResult As Object
Dim boolSchedDateFound As Boolean = False
For Each CurrentResult In ResultsB
If CurrentResult.Value <> CurrVal Then
'LogIntegrityCheckErrorRow()
End If
boolSchedDateFound = True
Next
Next
This takes FOREVER to run with 100,000 rows.
I've been trying to rewrite this as:
Dim MismatchRows = From TableAData In DataSetA.Tables(0).AsEnumerable() Join TableBData In DataSetB.Tables(15).AsEnumerable() _
On New With {.TableAID = Convert.ToInt32(TableAData("ID")), .TableATime = Convert.ToDateTime(TableAData("Date"))} _
Equals New With {.TableBDID = Convert.ToInt32(TableBData("ID")), .TableBTime = Convert.ToDateTime(TableBData("Time"))} _
Select .................. (Hard to clean up, but this isn't the part that's failing)
And I'm having a bear of a time with it. The fundamental problem is the lack of strong typing. I've looked, but there seems to be little advice because most people doing this build EF on the data. Which isn't a terrible idea, but would require a bunch of re-engineering. So. Problem in front of me, how do I remove the error:
'Equals' cannot compare a value of type '<anonymous type> (line 2641)' with a value of type '<anonymous type> (line 2642)'.
Thank you so much for your help.
Have you tried this?
Dim MismatchRows = From TableAData In ei _
Join TableBData In e2 On _
TableAData("ID") Equals TableBData("ID") And TableAData("Data") Equals TableBData("Time")
Select .......
db.tb_DeviceGeFenceDetail.Join(db.tb_InventoryLog, Function(gfd) gfd.DeviceID, Function(il) il.deviceId, Function(gfd, il) New From { _
gfd.GeFenceLat1, _
gfd.GeFenceLng1, _
gfd.GeFenceLat2, _
gfd.GeFenceLng2, _
il.deviceName, _
il.DeviceIcon, _
gfd.DeviceID, _
il.id _
}).ToList().Where(Function(y) intValues.Contains(y.id))
you can try joining tables something like this.