Return Unique Records for Field - ms-access

We have an access database create a csv list in an access table for each userid that logs into a computer. The problem is that if a userid logs in multiple times on one computer, than the userid is duplicated.
SO let's say this is what the table structure looks like
computer DailyUsers
ABC-123 ml12, rs12, ml12, ml12, ee13
DEF-456 zx44, aa33, zx44
And this is what I want a query to return
Computer DailyUsers
ABC-123 ml12, rs12, ee13
DEF-456 zx44, aa33
I tried using both Group By and Distinct but that looks on a row by row basis, not a field basis
How can this be achieved in Access 2013?

You can create a custom function in VBA to return only the unique users.
Add this in a VBA module:
Option Compare Database
Option Explicit
Public Function DistinctOnly(txt As String)
Dim arr, v, rv As String
Dim d As Object
arr = Split(txt, ",")
If UBound(arr) > 0 Then
Set d = CreateObject("scripting.dictionary")
For Each v In arr
d(Trim(v)) = 1
Next v
rv = Join(d.keys, ",")
Else
rv = txt
End If
DistinctOnly = rv
End Function
Usage:
SELECT Table1.[ID], Table1.[Users], DistinctOnly(Table1.[Users]) as UsersX
FROM Table1;
Input data and query results:

Related

how to get attachment files using union query in ms access

I have two independent tables in ms access now i want to get all data from both tables and show as one table using union query.
all is work but the problem is the attachment fields doesn't not loaded and its Empty.
SELECT *
FROM Table1
UNION ALL select * from Table2;
--This is my query which gets all records from both table but the attachment type field is empty
This example may be usefull
Set rsChild = rsDocs.Fields("DocText").Value
rsChild.Fields("FileData").SaveToFile newFileName
rsChild.Close
where rsDocs - ADO (or DAO) recordset as query result
DocText - attachment field name
rsChild.Fields("FileData") - stream object
SaveToFile - method of attachment field
rsDocs.Fields("DocText").Value.Fields("FileData").SaveToFile
The below example uses an attachment field named AttachmentField. You can pass the name of the file you're looking through the parameter.
If you run only the SQL, the parameter window will pop-up asking for the parameter value. To search, find the file and open it, you will need to use VBA.
See an example:
PARAMETERS [FileNameParam] Text (255);
SELECT T.ID, T.FileName
FROM (
SELECT ID, AttachmentField.FileName AS FileName
FROM Table1
UNION ALL
SELECT ID, AttachmentField.FileName AS FileName
FROM Table2
) AS T
WHERE T.FileName Like '*' + [FileNameParam] + '*'
Dim q As DAO.QueryDef
Set q = CurrentDb().QueryDefs("Query1")
q.Parameters("[FileNameParam]").Value = "Blank.pdf"
Dim r As DAO.Recordset
Set r = q.OpenRecordset(dbOpenSnapshot)
'nothing found
If r.EOF Then
MsgBox "File not found."
Exit Sub
End If
Dim filepath As String
filepath = r![FileName]
'open
Application.FollowHyperlink filepath
'clean up
If Not r Is Nothing Then r.Close
If Not q Is Nothing Then q.Close

Why is it entering the loop? vb net mysql

I m new to vb net
So here is my problem
My database has 1 table=quiz and 3 columns of ID ,name and Flag
All flags are set to '0'
Whenever I delete ,instead of deleting ,I update the name field to xxx and Flag to 1
In my database ,ID =3 has name = xxx
Still y is it entering the loop? and printing the msg"OH no"?
my code :
Dim SQL as String
SQL = "SELECT Name FROM quiz WHERE Flag='0' AND ID='3'"
c = 0
If SQL <> "xxx"Then
' Try, Catch, Finally
i = i + 1
MsgBox("Ohh no")
END IF

Convert a databound combobox's data to ProperCase in VB 2010

In VB 2010 I'm trying to show the DisplayMember in ProperCase without modifying my existing MySQL tables.
A snippet of my code looks like this:
Dim sql0 As String = "SELECT business, customer_id FROM customers WHERE cab = '1'"
Dim data0 As New MySqlDataAdapter(sql0, main.conn)
Dim ds0 As New DataSet
ds0.Clear()
data0.Fill(ds0, "customers")
cmb_company.DataSource = ds0
cmb_company.DisplayMember = "customers.business"
cmb_company.ValueMember = "customers.customer_id"
Ive tried something like this:
cmb_company.DisplayMember = StrConv("customers.business_name", VbStrConv.ProperCase)
but this only changes the case of the part in quotes, and not the actual returned values. I also tried querying from MySQL like this:
"SELECT UPPER(business), customer_id FROM customers WHERE cab = '1'"
but this fails to return the "business" field..
I'd love it if my combobox had proper case without changing everything.
I appreciate any suggestions!
Use the second one, but use an alias like this:
"SELECT UPPER(business) AS Business, customer_id FROM customers WHERE cab = '1'"
MySQL documentation:
A select_expr can be given an alias using AS alias_name. The alias is
used as the expression's column name and can be used in GROUP BY,
ORDER BY, or HAVING clauses. For example:
SELECT CONCAT(last_name,', ',first_name) AS full_name FROM mytable
ORDER BY full_name;
It seems a bit silly to use a while loop to achieve this especially after filling the table with an adapter. I suppose I could have just skipped the .fill and added the items manually through the loop, all while ProperCasing them. Anyway, here is my code:
Dim sql1 As String = "SELECT * FROM table"
Dim data1 As New MySqlDataAdapter(sql1, main.conn)
Dim ds1 As New DataSet
ds1.Clear()
data1.Fill(ds1, "table")
cmb_buyout.DataSource = ds1
Dim i As Integer = 0
While i < ds1.Tables(0).Rows.Count
Dim name As String = StrConv(ds1.Tables(0).Rows(i).Item(1).ToString, VbStrConv.ProperCase)
ds1.Tables(0).Rows(i).Item(1) = name
i += 1
End While
cmb_buyout.DisplayMember = "table.buyoutType"
cmb_buyout.ValueMember = "table.id"
To anyone trying to accomplish this, it is probably simpler to just change the case on the entries in the DB. I might just end up doing this!

Getting the value not the ID

I have a table tblInvestigators which contains a lookup field to display a list of names
A grant may have more than 1 investigator.
A requirement of my project is to list all investigators in a single cell next to the grant details, so i'd have:
Grant A | Name A, Name B, Name C
etc.
I have a VBA module that concatenates the investigators into 1 cell as follows:
'Concat Returns lists of items which are within a grouped field
Public Function c(strID As String, strAddMe As String) As String
Static prevID As String
Static strFinal As String
Static strLastAdded As String
If (strID = prevID And strAddMe <> strLastAdded) Then
strFinal = strFinal & ", " & strAddMe
Else
prevID = strID
strLastAdded = strAddMe
strFinal = strAddMe
End If
c = strFinal
End Function
And an access query that calls it (SQL):
SELECT g.grant_id, Max(c(g.grant_id,tblInvestigators.investigator)) AS Expr1
FROM tblGrants AS g LEFT JOIN tblInvestigators ON g.grant_id = tblInvestigators.grant_id
WHERE (((g.grant_id)=6))
GROUP BY g.grant_id;
When I run this, it returns a comma separated list, but it is a list of the ID numbers from the look up column (tblInvestigators.investigator)rather than the names. How can I get the names?
Chris
It is never a good idea to use look-up fields: http://www.mvps.org/access/lookupfields.htm
It is disguising the standard way of getting the results you want, which is to use a query to join the ID to the look-up table and return the description.
Have a look at this Does MS access(2003) have anything comparable to Stored procedure. I want to run a complex query in MS acceess

Linq to SQL - How to verify a record doesn't exists before inserting

I'm working on a little side app for a client whereby they provide me with a list of cities and I have to insert them into the database and associate them with their parent records.
Example:
ID | PID | Region
1 0 California
2 1 Los Angeles
3 1 San Fransisco
Now my code looks like this
Dim input As StreamReader
Dim index As Integer
Dim filename As String
Dim RegionDC As New DAL.RegionsDataContext
For Each TextFile As String In Directory.GetFiles(Server.MapPath("~/app_data/business-trader cities/"))
input = File.OpenText(TextFile)
filename = New FileInfo(TextFile).Name
index = 0
''# this is where we want to select the ID for the filename'
Dim _ID = (From R In RegionDC.bt_Regions _
Where R.Region = filename.Replace(".txt", "") _
Select R.ID).FirstOrDefault
While Not input.EndOfStream
Dim q = (From r In RegionDC.bt_Regions _
Where r.Region = input.ReadLine() _
Select r.ID).FirstOrDefault
''# ***********************************'
''# HERE IS WHERE IM TRYING TO VERIFY'
''# IF THE RECORD EXISTS OR NOT'
''# ***********************************'
''# now we loop through the txt file'
''# and insert the data into the database'
Dim oRegion As New DAL.bt_Region
oRegion.Region = input.ReadLine()
oRegion.FSSearchCount = 0
oRegion.WSearchCount = 0
oRegion.PID = _ID
RegionDC.bt_Regions.InsertOnSubmit(oRegion)
RegionDC.SubmitChanges()
End While
''# clean up the locked files'
input.Close()
input.Dispose()
Next
So basically if Los Angeles is in the TXT file, I don't want it re-entered into the database since it already exists.
Can anyone help me figure out how to verify if a record already exists prior to inserting?
LINQ To SQL Samples - EXISTS/IN/ANY/ALL
Public Sub LinqToSqlExists01()
Dim q = From c In db.Customers _
Where Not c.Orders.Any()
ObjectDumper.Write(q)
End Sub
Assuming that no record can have ID of 0, I think it's just a matter of testing whether q = 0.
But I think you have a bug in the code: you call input.ReadLine() twice in each iteration, so you test whether Los Angeles is already in the database and then try to insert San Francisco. Just capture the line in a variable and then use that.
if (RegionDC.bt_Regions.Any(r => r.Region == input.ReadLine()))
{
// Yes it exists
}
else
{
// No it doesn't exist
}
Used a converter to make the VB version :)
If RegionDC.bt_Regions.Any(Function(r) r.Region = input.ReadLine()) Then
''# Yes it exists
Else
''# No it doesn't exist
End If