I am trying to check if a value isl Resistant in a table from a Form using dlookup - vba

I am trying to lookup a value in a table for a particular patient ID and see whether that patient has the value Resistant. If so then disable a particular button on the form. I tried the following dlookup but it's giving me compiler error:
If DLookup("Rifampicin", "TableGeneXpert", "[PatientID] = " & Forms.FrmTreatment!PatientID) = Resistant Then
Me.btnDSTMatch.Enabled = True
Else
Me.btnDSTMatch.Enabled = False

Try with:
If DLookup("Rifampicin", "TableGeneXpert", "[PatientID] = " & Forms.FrmTreatment!PatientID & "") = "Resistant" Then
Me.btnDSTMatch.Enabled = True
Else
Me.btnDSTMatch.Enabled = False
End If
Or perhaps directly:
Me.btnDSTMatch.Enabled = IsNull(DLookup("Rifampicin", "TableGeneXpert", "[PatientID] = " & Forms.FrmTreatment!PatientID & " And [Rifampicin] = 'Resistant'"))
To filter on the latest date you can include a DMax expression or (the little known option) an SQL filter:
Me.btnDSTMatch.Enabled = IsNull(DLookup("Rifampicin", "TableGeneXpert", "[PatientID] = " & Forms.FrmTreatment!PatientID & " And [Rifampicin] = 'Resistant' And [JournalDate] = (Select Max([JournalDate]) From TableGeneXpert Where [PatientID] = " & Forms.FrmTreatment!PatientID & " And [Rifampicin] = 'Resistant')"))

Related

VBA gives a negative value when should give a positive

I'm trying to set the value of the field p_person as 1 when the bbp.ind=Y.
SqlStmt = "UPDATE person " & _
" SET p_person = 1 " & _
" FROM Person p INNER JOIN " & PersonTableName &
" bbp ON p.personID = bbp.personID " & _
" WHERE bbp.ind = 'Y' " & BBPersonsManual_Filter_and
SqlConn.Execute SqlStmt, RecordsAffected
LogRecords "Update p_person", Str(RecordsAffected)
Instead of 1, the value is being defined as -1 when the value of the bbp.ind=Y.
How can I solve this?
If this is a Boolean column, then 0 will be interpreted as False and any value unequal 0 will be treated as True. The standard value for True is -1 in an Access table.
So, this behavior is expected. When you test the value of a Boolean column (a Yes/No column) don't test p_person = 1 or p_person <> 1. Instead test p_person <> 0 or p_person = 0. Like this it does not matter whether there is 1 or -1 in the column.

Access Run Time Error 3464 data type mismatch in criteria expression

What is wrong with that code? I can't figure out why I keep getting this error.
Sub renttt()
Dim rent_list As Recordset
Dim query As String
query = "SELECT * FROM (Rent INNER JOIN Movies ON Rent.Movie_ID = Movies.ID) INNER JOIN Customers ON Rent.Customer_ID = Customers.ID WHERE Rent.Movie_ID = '" & txtbxmovieID.Value & "' AND Rent.Date_Returned is Null;"
Set rent_list = CurrentDb.OpenRecordset(query)
If rent_list.RecordCount = 1 Then
rent_List.MoveFirst
txtbxname.Value = (rent_list![CusName])
txtbxsurname.Value = (rent_list![Surname])
txtbxcardID.Value = (rent_list![Id_Card_number])
txtbxaddress.Value = (rent_list![Address])
txtbxrented.Value = (rent_list![Date_Rent])
End If
End Sub
Wouldn't MovieId be a numeric? If so, no quotes:
WHERE Rent.Movie_ID = " & txtbxmovieID.Value & " AND ...

SQL Syntax error, expression of non-boolean type

This code is supposed to create a graph of revenue from money made through sales tickets at an event.
The code only executes up to da.Fill(ds) when it returns the error, which can be seen at the end of the code.
Does anybody know why
Private Sub frmRevenue_Load(sender As Object, e As EventArgs) Handles Me.Load
frmMDI.addFormToCMS()
Dim dt As DataTable
dt = New DataTable
dt.Columns.Add("Fee")
Dim sales As Integer = 0
Dim gridtable As New DataTable
gridtable.Columns.Add("Month")
gridtable.Columns.Add("Total")
gridtable.Columns.Add("#")
For i = 1 To 12
sql = "SELECT Fee FROM tblTickets WHERE MONTH(DatePurchased) = " & i & " AND (YEAR(DatePurchased) = " & Today.Year & " OR " & Year(Today.AddYears(1)) & ") AND (Status = 'SOLD' OR RESERVED" _
& " = 'AWAITING CONFIRMATION' OR Status = 'AVAILABLE' OR Status = 'AWAITING PAYMENT');"
da = New OleDb.OleDbDataAdapter(sql, con)
ds = New DataSet
da.Fill(ds)
Dim dr As DataRow
For Each dr In ds.Tables(0).Rows
monthly(i) = monthly(i) + 1
contracts = sales + 1
total(i) = total(i) + dr.Item("Fee")
yearlytotal = yearlytotal + dr.Item("Fee")
Next
Next
For i = 1 To 12
Dim month As String
Select Case i
Case 1
month = "Jan"
Case 2
month = "Feb"
Case 3
month = "Mar"
Case 4
month = "Apr"
Case 5
month = "May"
Case 6
month = "Jun"
Case 7
month = "Jul"
Case 8
month = "Aug"
Case 9
month = "Sep"
Case 10
month = "Oct"
Case 11
month = "Nov"
Case 12
month = "Dec"
Case Else
month = "ERR"
End Select
gridtable.Rows.Add(month, FormatCurrency(total(i)), monthly(i))
Next
ugTickets.DataSource = gridtable
ugTickets.DisplayLayout.Bands(0).Columns("Month").Width = 35
ugTickets.DisplayLayout.Bands(0).Columns("#").Width = 20
ugTickets.DisplayLayout.Override.AllowUpdate = DefaultableBoolean.False
txtAnnual.ReadOnly = True
txtAnnual.BackColor = Color.White
txtAnnualContracts.ReadOnly = True
txtAnnualContracts.BackColor = Color.White
chRevenue.Titles("chTitle").Text = "Predicted revenue for " & Today.Year & " - " & Year(Today.AddYears(1))
txtAnnual.Text = FormatCurrency(yearlytotal, 2)
txtAnnualContracts.Text = contracts
chRevenue.Series("Series1").Name = "Revenue"
For i = 1 To 12
chRevenue.Series("Revenue").Points.AddY(total(i))
Next
Try
chRevenue.BackColor = Color.Transparent
chRevenue.Legends("Revenue").BackColor = Color.Transparent
chRevenue.Series("Revenue").ChartArea = "ChartArea1"
chRevenue.Series("Revenue").Color = Color.SkyBlue
chRevenue.Series("Revenue").ToolTip = FormatCurrency("#VALY", 2)
Catch
End Try
End Sub
An expression of non-boolean type specified in a context where a condition is expected, near ')'.
The problem is with this bit of the SQL:
(YEAR(DatePurchased) = " & Today.Year & " OR " & Year(Today.AddYears(1)) & ")
It should probably be
(YEAR(DatePurchased) = " & Today.Year & " OR YEAR(DatePurchased) = " & Year(Today.AddYears(1)) & ")
The OR in SQL (and in most other languages) needs to have two independently valid conditions on each side. The left hand side currently looks like this:
YEAR(DatePurchased) = 2016
...which is fine. But the right looks like this:
2017
...which isn't a valid boolean.
When you get an error like this on the da.Fill() line (ie. the line that's actually running the SQL in the database), the easiest way to debug it is to print out the value of the "sql" variable.
Often, you can just look at the SQL it's generated and the problem will be obvious. Other times you have to copy it and run it directly against your database to see what the problem is.
Might be your SQL, try:
"SELECT Fee FROM tblTickets WHERE MONTH(DatePurchased) = '" & i &
"' AND (YEAR(DatePurchased) = '" & Today.Year &
"' OR '" & Year(Today.AddYears(1)) & "') " &
"AND (Status = 'SOLD' OR RESERVED = 'AWAITING CONFIRMATION' " &
"OR Status = 'AVAILABLE' " &
"OR Status = 'AWAITING PAYMENT');"

vb.net - using case select query in sql for jtable

If anyone knows how to use case in query for jtable, pls take a look my code.
Dim batch_status As String = " case when status = 0 then 'Created' when status = 1 then 'Scanning' when status = 2 then 'Scan Saved' end as status"
cmd.CommandText = "SELECT * FROM ( SELECT ROW_NUMBER() OVER ( ORDER BY " & jtSorting & " ) AS RowNum, batch_id, batch_name, date_created, profile_id, total_page, " & batch_status & ", First_ScanID, file_id " & _
" FROM [ip_ent_site].[dbo].[tbl_batch] WHERE STATUS IN (0,1,2) ) AS RowConstrainedResult " & _
" WHERE RowNum >= #jtStartIndex AND RowNum < #jtEndIndex ORDER BY RowNum ; "
if i use like this, it is working:
Dim batch_status As String = "status"
but with case, not.
whats problem here?
another part of code:
If dt.Rows.Count > 0 Then
students = (From item In dt.AsEnumerable() Select New Class1 With { _
.No = Convert.ToInt32(item(1)), _
.batch_id = Convert.ToInt64(item(2)), _
.batch_name = DirectCast(item(3), String), _
.date_created = item(4).ToString, _
.profile_id = Convert.ToInt32(item(5)), _
.total_page = Convert.ToInt32(item(6)), _
.status = Convert.ToInt32(item(7)), _
.First_ScanID = Convert.ToInt32(item(8)), _
.file_id = CheckDBNullInteger(item(9)) _
}).ToList()
End If
Use your declare statement like below.
Dim batch_status As String = " case when status = 0 then ''Created'' when status = 1 then ''Scanning'' when status = 2 then ''Scan Saved'' end as status"
may be the problem with #jtStartIndex AND #jtEndIndex.
Just found, change .status = Convert.ToInt32(item(7)) to .status = item(7).ToString,
displaying in Jtable is quite different

SQLite terribly slow compared to MS Access

Following the advice of fellow SO-ers, I converted an MS Access database I had (a small one, for test reasons) to SQLite. It has two tables, one with 5k entries and another with 50k entries.
Now, the queries I will present below QuLimma and QLexeis took about 60ms (total time of the function below) with Access, but a whopping 830ms with SQLite.
Dim i As Integer
Dim ms As Integer
ResultPin(0) = ""
ResultPin(1) = ""
ResultPin(2) = ""
ResultPin(3) = ""
ResultPin(4) = ""
i = 0
Multichoice = 0
ms = 0
Dim rsTblEntries As ADODB.Recordset
Set rsTblEntries = New ADODB.Recordset
Dim QuLimma As String, QLexeis As String
QuLimma = "SELECT Words.limma, Words.limmabody, Words.limmapro " & _
"FROM Words " & _
"GROUP BY Words.limma, Words.limmabody, Words.limmapro " & _
"HAVING (((Words.limma)='" & StrLexeis & "'));"
QLexeis = "SELECT Limma.limmalexeis, Words.limma, Limma.limmabody, Words.limmapro, Limma.limmaexp " & _
"FROM Limma INNER JOIN Words ON Limma.limmabody = Words.limmabody " & _
"GROUP BY Limma.limmalexeis, Words.limma, Limma.limmabody, Words.limmapro, Limma.limmaexp " & _
"HAVING (((Limma.limmalexeis)='" & StrLexeis & "'));"
rsTblEntries.Open QuLimma, CnDataParSQLite ', adOpenStatic, adLockOptimistic
If rsTblEntries.EOF = True Then
rsTblEntries.Close
rsTblEntries.Open QLexeis, CnDataParSQLite ', adOpenStatic, adLockOptimistic
If rsTblEntries.EOF = True Then
SearchQParagSQLite = False
Else
SearchQParagSQLite = True
Do While rsTblEntries.EOF = False
ms = ms + 1
rsTblEntries.MoveNext
Loop
rsTblEntries.MoveFirst
If ms > 1 Then
Do While rsTblEntries.EOF = False
ResultTemp(0, i) = rsTblEntries.Fields("limma").Value & "" 'rsWordPar!limma
ResultTemp(1, i) = rsTblEntries.Fields("limmalexeis").Value & "" 'rsWordPar!limmalexeis
ResultTemp(2, i) = rsTblEntries.Fields("limmabody").Value 'rsWordPar!limmabody
If IsNull(rsTblEntries.Fields("limmapro").Value) = False Then ResultTemp(3, i) = rsTblEntries.Fields("limmapro").Value 'rsWordPar!limmapro
rsTblEntries.MoveNext
i = i + 1
Multichoice = 1
Loop
Else
Do While rsTblEntries.EOF = False
ResultPin(0) = rsTblEntries.Fields("limma").Value & "" 'rsWordPar!limma
ResultPin(1) = rsTblEntries.Fields("limmalexeis").Value & "" 'rsWordPar!limmalexeis
ResultPin(2) = rsTblEntries.Fields("limmabody").Value 'rsWordPar!limmabody
If IsNull(rsTblEntries.Fields("limmapro").Value) = False Then ResultPin(3) = rsTblEntries.Fields("limmapro").Value 'rsWordPar!limmapro
rsTblEntries.MoveNext
Multichoice = 0
Loop
End If
End If
Else
SearchQParagSQLite = True
rsTblEntries.MoveFirst
Do While rsTblEntries.EOF = False
ResultPin(0) = rsTblEntries.Fields("limma").Value & "" 'rsWordPar!limma
ResultPin(1) = "#"
ResultPin(2) = rsTblEntries.Fields("limmabody").Value 'rsWordPar!limmabody
If IsNull(rsTblEntries.Fields("limmapro").Value) = False Then ResultPin(3) = rsTblEntries.Fields("limmapro").Value 'rsWordPar!limmapro
rsTblEntries.MoveNext
i = i + 1
Loop
End If
i = 0
rsTblEntries.Close
Set rsTblEntries = Nothing
With connection string:
CnDataParSQLite.ConnectionString = "DRIVER=SQLite3 ODBC Driver;" & _
"Database=" & strDataPath & "u.sl3;LongNames=0;Timeout=1000;NoTXN=0;SyncPragma=NORMAL;StepAPI=0;"
CnDataParSQLite.Open
Now, before someone asks "wasn't 60ms fast enough?", I'd like to say that I did this because I have other Access files and queries which take 3-4 seconds and would like to lower them down, so yes, I was hoping to go down from 60ms to 30 or less in this one.
Do I have a misconfiguration or is it just that SQLite is not faster? I have checked, both return correct results, there is no weird looping issue.
Edit: most of the time is consumed by the second query.
Edit 2: (copy/paste from the db.sql)
Table Limma:
CREATE TABLE Limma ( id INTEGER PRIMARY KEY, limmabody INTEGER DEFAULT 0, limmalexeis VARCHAR2(100), limmastat VARCHAR2(50), limmaexp VARCHAR2(250));
INSERT INTO Limma VALUES (1, 1, 'υψικάμινος', 'ΣΠ', NULL);
INSERT INTO Limma VALUES (2, 1, 'υψίκορμος', 'ΣΠ', NULL);
INSERT INTO Limma VALUES (3, 1, 'υψίπεδο', 'ΑΠ', '<αρχ. υψίπεδον, ουδ. του επιθ. υψίπεδος<ύψι "ψηλά" + πέδον');
Total: 64k entries
Table Words:
CREATE TABLE Words ( id INTEGER PRIMARY KEY, limma VARCHAR2(100), limmabody INTEGER DEFAULT 0, limmapro VARCHAR2(200));
INSERT INTO Words VALUES (1, 'υψι (αχώριστο μόριο)', 1, NULL);
INSERT INTO Words VALUES (2, 'ομο (αχώριστο μόριο)', 2, NULL);
INSERT INTO Words VALUES (3, 'διχο (αχώριστο μόριο)', 3, NULL);
Total: 6k entries
The first field "id" is unique.
You almost never want to use HAVING where you can use WHERE criteria. You're evaluating all possible results and then culling them down after aggregation. You mainly want to use HAVING criteria where you're trying to cull down based upon the aggregated results. You can achieve the same thing by moving the HAVING logic to a WHERE criteria before the aggregation in this case. This should greatly speed up your query.
There is also no need to use GROUP BY logic since you're not returning any aggregates, just use DISTINCT.
I would write it like this:
QuLimma = "SELECT DISTINCT Words.limma, Words.limmabody, Words.limmapro " & _
"FROM Words " & _
"WHERE Words.limma ='" & StrLexeis & "';"
QLexeis = "SELECT DISTINCT Limma.limmalexeis, Words.limma, Limma.limmabody, Words.limmapro, Limma.limmaexp " & _
"FROM Limma INNER JOIN Words ON Limma.limmabody = Words.limmabody " & _
"WHERE Limma.limmalexeis ='" & StrLexeis & "';"
For these two queries with your table schema these indexes should optimize the queries:
CREATE NONCLUSTERED INDEX ix_words_1 ON Words (Limma) INCLUDE (Limmabody, Limmapro)
CREATE NONCLUSTERED INDEX ix_words_2 ON Words (Limmabody) INCLUDE (Limma, Limmapro)
CREATE NONCLUSTERED INDEX ix_limma_1 ON Limma (Limmabody, Limmalexeis) INCLUDE (Limmaexp)
Keep in mind there is a cost at the time of insert for each additional index you have. You have to weigh this cost against the benefit of the index. If your tables contain static data then there is no harm.