Concatrelated with two parameters - sql

I am trying to use Allen Browne's ConcatRelated function in a database for City Council Ordinances. I have one working properly, but this one in an unbound field should produce a string of councilor names of those who voted yes. It has two parameters and keeps returning a 3601 error, too few parameters. Votes are tallied as 'Y' or 'N'. I will need a sister string for 'N'
=ConcatRelated("[Lname]","[qryVoteTally2]","CO2_IDfk =" & [CO2_ID] & " AND " & "Vote = 'Y'")
The underlying SQL is
SELECT mmVotes.CO_ID2fk, mmVotes.Vote, tblSponsors.Lname
FROM mmVotes LEFT JOIN tblSponsors ON mmVotes.Counc_ID = tblSponsors.Spon_ID
The query works on its own. Why?

Related

Allen Browne's ConcatRelated() Error 3061: Too few parameters

I am trying to create a list of products at a given warehouse.
Allen Browne's ConcatRelated() function seems to be the tried and true method to create lists using when a linked variable is the same, but I can't get it to work.
I have broken my information down into a single query... "qry_Products"
SELECT qry_AX_LineItems_LINES.Warehouse, tblREF_Chemical.[Sales Name]
FROM qry_AX_LineItems_LINES INNER JOIN tblREF_Chemical ON
qry_AX_LineItems_LINES.ItemId = tblREF_Chemical.[Item Number]
GROUP BY qry_AX_LineItems_LINES.Warehouse, tblREF_Chemical.[Sales Name];
It produces a table with the Sales Name and Warehouse(s).
What I need to see happen is a list of the Sales Names when their warehouse matches.
I have tried using the function in a textbox of my form...
=ConcatRelated("[Sales Name]","[qry_Products]"," Warehouse ='" & [Warehouse]
& "'")
It causes an Error 3061 and leaves the cell blank.
I double checked my syntax within the quotes by using Dlookup(), and it produced the first result of the list.
I have also tried altering my query...
SELECT qry_AX_LineItems_LINES.Warehouse, ConcatRelated("[Sales Name]","
[tblREF_Chemical]") AS Expr1
FROM qry_AX_LineItems_LINES INNER JOIN tblREF_Chemical ON
qry_AX_LineItems_LINES.ItemId = tblREF_Chemical.[Item Number];
Unfortunately it then lists every product in my database as a list.
I also tried creating a new query to reference the one producing minimal information.
SELECT ConcatRelated("[Sales Name]","qry_Products") AS Expr1
FROM qry_Products;
I know that the initial query is correct but when I go to run the new query I get multiple pop-ups of Error 3061 and empty cells for results.
I double checked that I am copying the module exactly. http://allenbrowne.com/func-concat.html
Module is named "Concat".
I'm reading every help guide out there but I just can't see what I should try next.
Thank you so much for time and any advice!
SubForm frm_LineItems
Query qry_Products
I found another thread that gives an alternative to the Allen Browne method.
https://bytes.com/topic/access/answers/569535-combining-rows-opposite-union
This seems to be working.
'Concat Returns lists of items which are within a grouped field
Public Function Concat(strGroup As String, strItem As String) As String
Static strLastGroup As String
Static strItems As String
If strGroup = strLastGroup Then
strItems = strItems & ", " & strItem
Else
strLastGroup = strGroup
strItems = strItem
End If
Concat = strItems
End Function
with Query SQL
SELECT WH,
Max(Concat(WH, [Sales Name])) AS Products
FROM [qry_Products]
GROUP BY WH
I wanted to leave this here in case anyone else was having a similar issue.

How do I access multiple records from the same table using SQLDataAdapter?

This almost works. I get an error at the last line that looks like it's complaining about the C1 reference. Is there a simple way around this? There is nothing wrong with the query or connection.
Dim CmdString As String
Dim con As New SqlConnection
Try
con.ConnectionString = PubConn
CmdString = "select * from " & PubDB & ".dbo.Suppliers as S " & _
" join " & PubDB & ".dbo.Address as A" & _
" on S.Supplier_Address_Code = A.Address_IDX" & _
" join " & PubDB & ".dbo.Contacts as C1" & _
" on S.Supplier_Contact1 = C1.Contact_IDX" &
" join " & PubDB & ".dbo.Contacts as C2" & _
" on S.Supplier_Contact2 = C2.Contact_IDX" &
" WHERE S.Supplier_IDX = " & LookupIDX
Dim cmd As New SqlCommand(CmdString)
cmd.Connection = con
con.Open()
Dim DAdapt As New SqlClient.SqlDataAdapter(cmd)
Dim Dset As New DataSet
DAdapt.Fill(Dset)
con.Close()
With Dset.Tables(0).Rows(0)
txtAddress1.Text = .Item("Address1").ToString
txtAddress2.Text = .Item("Address2").ToString
txtSupplierName.Text = .Item("Address_Title").ToString
txtAttn.Text = .Item("Attn").ToString
txtBusinessPhone1.Text = .Item("C1.Contact_Business_Phone").ToString
You would not include the "C1" table alias as part of your column name. It will be returned from your query as Contact_Business_Phone.
For accessing multiple rows you could use the indexer as you are in the example above "Rows(0)" by placing your With block into a For loop and accessing the "Rows(i)" with your loop variable. However, this would not help much as your are assigning this to individual text boxes, so you'd only see the last value on your page/screen.
The alias C1 is used by SQL Server and is not persisted to the result set. Have you taken this query into SQL Management Studio to see the results?
Since you requested all columns (*) and joined to the Contacts table twice, you'll end up with duplicate column names in the result. For example, if the Contacts table has a LastName field, you'll end up with TWO LastName columns in your result.
I haven't tried to duplicate this in my local environment, but I can't imagine the data adapter is going to like having duplicate column names.
I recommend specifically including the columns you want to return instead of using the *. That's where you'll use the alias of C1, then you can rename the duplicate columns using the AS keyword:
SELECT C1.LastName AS [Supplier1_LastName],
C2.LastName AS [Supplier2_LastName],
...
This should solve your problem.
Good Luck!
You should only be pulling back the columns that you're in fact interested in, as opposed to *. It's sort of hard to tell exactly what data exists in which tables since you're pulling the full set, but at a quick guess, you'll want in your select statement to pull back A.Address1, A.Address2, A.AddressTitle, ?.Attn (not sure which table this actually derives from) and C1.Contact_Business_Phone. Unless you actually NEED the other fields, you're much better off specifying the individual fields in your query, besides having the possible duplicate field issue that you're running into here, it can also be a significant performance hit pulling everything in. After you clean up the query and only pull in the results you want, you can safely just reference them the way you are for the other fields, without needing a table alias (which as others have pointed out, isn't persisted to the result set anyways).

Access 2007 VBA: Returning data from SQL statements that use multiple variables

I am working on a form that is meant to analyze financial data ahead of an insurance policy renewal. It needs to pull various premium and claim $$ totals from the tables, and insert them into the form. From there, it will run some calculations with them, but that should be the easy part. Where I'm struggling is the SQL statements to get the data, in the first place.
After narrowing it down a bit, I've found that the problem is the code is putting the SQL statement into the field on the form, instead of the answer the SQL statement should be providing. I have tried multiple things I've seen online, and can't figure out how to resolve this.
One of the SQL statements reads like this:
L12W = "SELECT Sum(tblActPrem.APWrit) AS SumOfAPWrit FROM tblActPrem " _
& " WHERE tblActPrem.EntID = '" & Me.ctlActEntID & "' " _
& " AND tblActPrem.PolNum = '" & Me.ctltblRnwlTrack_PolNum & "'" _
& " AND tblActPrem.APDate BETWEEN #" & L12M & "# AND #" & Me.ctlRnwAnalysisDt & "#;"""
It should be totalling premium data from the table, where the policy number and account number match what's on the form, and between the selected dates, and putting that total into the field on the form. Instead, I get this on the form:
SELECT Sum(tblActPrem.APWrit) AS SumOfAPWrit FROM tblActPrem WHERE tblActPrem.EntID = '1235' AND tblActPrem.PolNum = 'Policy1' AND tblActPrem.APDate BETWEEN #1/1/2014# AND #1/1/2015#;"
That is exactly how the statement should be running, but can anyone tell me how to make the leap from the statement, to the data?
Thank you!
Consider using DLookup or DSum in the control source of the form's field.
DLookup Solution
First, change your VBA SQL query into a stored SQL Query (notice quotes and # symbols are not necessary when referencing form controls):
SELECT Sum(tblActPrem.APWrit) AS SumOfAPWrit
FROM tblActPrem
WHERE tblActPrem.EntID = Forms!<yourformname>!ctlActEntID
AND tblActPrem.PolNum = Forms!<yourformname>!ctltblRnwlTrack_PolNum
AND tblActPrem.APDate BETWEEN Forms!<yourformname>!L12M
AND Forms!<yourformname>!ctlRnwAnalysisDt
And then in the form field textbox's control source use the DLookUp function (no criteria argument is needed since this should return only one value).
= DLookUp("SumOfAPWrit", "<yournewqueryname>")
DSum Solution
Alternatively, you can change the entire SQL statement into a DSum but notice how long the criteria (WHERE statement) would have to be.
= DSum("APWrit", "tblActPrem", "EntID = Forms!<yourformname>!ctlActEntID
AND PolNum = Forms!<yourformname>!ctltblRnwlTrack_PolNum
AND APDate BETWEEN Forms!<yourformname>!L12M AND Forms!<yourformname>!ctlRnwAnalysisDt")

Brackets in Access Query Using ConcatRelated Function

I'm attempting to concatenate multiple records of field "dbo_race.racedesc" into one record based on username. I'm attempting to use the ConcatRelated function (http://allenbrowne.com/func-concat.html). As the username is text, I followed the article's example to include extra quotes.
The error I get is "Error 3126: Invalid bracketing of name '[dbo_indrace.username]'."
The error seems to be referring to the period within the brackets. However, if I only list the field without the table name, I am prompted that it could refer to more than one table listed in my FROM clause.
What would be the correct syntax for the ConcatRelated function?
SELECT DISTINCT dbo_ind.username,
ConcatRelated("[racedesc]", "[dbo_race]", "[dbo_indrace.username] = """ & [dbo_ind.username] & """") AS racedescription
FROM dbo_race INNER JOIN (dbo_ind INNER JOIN dbo_indrace ON dbo_ind.username = dbo_indrace.username) ON dbo_race.race = dbo_indrace.race
WHERE dbo_race.lang='E';
Try changing [dbo_indrace.username] to [dbo_indrace].[username]
Same with [dbo_ind.username]

How do I save the result of an SQL COUNT query with VBA in Access 2007?

I'm trying to count the number of records in a table that meet a certain criteria. My preference is to use SQL, not Dcount, as I want to get better at SQL. Here's my current code below:
Dim countString As String
Dim count
countString = "SELECT COUNT(*) FROM `Engagement Letters` WHERE 'Client ID' = " & Me.cboSelectClient
count = CurrentDb.OpenRecordset(countString).Fields(0).Value
Yeah I know, I've used spaces in my tables and field names - I will change that. Though I think I should still be able to run this query as is, so I will leave it as is for now.
When I run the above, I get runtime error 3464 - data type mismatch in criteria expression. I've had the below dcount function work fine:
count = DCount("[Engagement Letter ID]", "Engagement Letters", "[Client ID] = " & Me.cboSelectClient)
And also the below COUNT query without the WHERE works fine:
"SELECT COUNT(*) FROM `Engagement Letters`"
My knowledge of SQL is very minimal, and my knowledge of more advanced VBA is also quite minimal, so I'm not sure where I'm going wrong. Can anyone help me with this?
Try building your string like this.
countString = "SELECT COUNT(*) FROM [Engagement Letters]" & vbCrLf & _
"WHERE [Client ID] = " & Me.cboSelectClient
Debug.Print countString
Use square brackets around object (table and field) names which include spaces or any characters other than letters, digits, and the underscore character.
For the table name, you used `Engagement Letters`, and the backticks appear to work the same as square brackets. Perhaps they always work equally well, but I don't know for sure because I use the brackets exclusively. And brackets instead of backticks might help you avoid this mistake ...
WHERE 'Client ID' = " & Me.cboSelectClient
... that was asking the db engine to compare the literal string, "Client ID", to the numerical value (?) you pulled from cboSelectClient.
I used vbCrLf between the 2 parts of the SELECT statement because I find that convenient when examining the completed string (via Debug.Print).