Solved

sql code to sort dconcat

Posted on 2010-11-18
13
462 Views
Last Modified: 2012-05-10
The first code sample links on a text field (ancestor number) and sorts the contents of the dconcat on each record based on child date of birth.

The second code sample links on an integer field(ancestorCID) but I can't figure out how to parse the syntax to accomplish sorting the contents of the dconcat by date of birth (as they are in the top sample.)  I keep getting invalid syntax errors.  I just can't figure out what all those " and ' are for!

Thanks, Karen
Children: "Children:" & " " & Nz(DConcat("[Child First Name],[child date of birth], [Child Spouse Name]","[ancestor children]","[Ancestor Number] = '" & [Ancestor Number] & "'","; "," ",True," [child date of birth] ASC "),"")



ListChildren2: "Children:" & Nz(DConcat("[Child First Name], [child date of birth], [Child Spouse Name]","[ancestor children]","[AncestorCID] = " & [AncestorCID]),"")

Open in new window

0
Comment
Question by:ksilvoso
13 Comments
 
LVL 84
ID: 34171924
What is "DConcat"? Is that a function you built? If so, can you post the code for that function?
0
 
LVL 1

Author Comment

by:ksilvoso
ID: 34172268
Here's the code.  Thanks again to MatthewsPatrick who built the code.

Option Compare Database
Option Explicit

Function DConcat(ConcatColumns As String, tbl As String, Optional Criteria As String = "", _
    Optional Delimiter1 As String = "; ", Optional Delimiter2 As String = " ", _
    Optional Distinct As Boolean = True, Optional OrderBy As String = "", _
    Optional Limit As Long = 0)
   
    ' Function by Patrick G. Matthews, basically embellishing an approach seen in many
    ' incarnations over the years
   
    ' Requires reference to Microsoft DAO library
   
    ' This function is intended as a "domain aggregate" that concatenates (and delimits) the
    ' various values rather than the more usual Count, Sum, Min, Max, etc.  For example:
    '
    '    Select Field1, DConcat("Field2", "SomeTable", "[Field1] = '" & Field1 & "'") AS List
    '    FROM SomeTable
    '    GROUP BY Field1
    '
    ' will return the distinct values of Field1, along with a concatenated list of all the
    ' distinct Field2 values associated with each Field1 value.
   
    ' ConcatColumns is a comma-delimited list of columns to be concatenated (typically just
    '   one column, but the function accommodates multiple).  Place field names in square
    '   brackets if they do not meet the customary rules for naming DB objects
    ' Tbl is the table/query the data are pulled from.  Place table name in square brackets
    '   if they do not meet the customary rules for naming DB objects
    ' Criteria (optional) are the criteria to be applied in the grouping.  Be sure to use And
    '   or Or as needed to build the right logic, and to encase text values in single quotes
    '   and dates in #
    ' Delimiter1 (optional) is the delimiter used in the concatenation (default is ", ").
    '   Delimiter1 is applied to each row in the code query's result set
    ' Delimiter2 (optional) is the delimiter used in concatenating each column in the result
    '   set if ConcatColumns specifies more than one column (default is ", ")
    ' Distinct (optional) determines whether the distinct values are concatenated (True,
    '   default), or whether all values are concatenated (and thus may get repeated)
    ' OrderBy (optional) indicates how to sort the results.  The argument value should consist
    '   of an entire ORDER BY clause (without the actual words "ORDER BY"), or be omitted
    ' Limit (optional) places a limit on how many items are placed into the concatenated string.
    '   The Limit argument works as a TOP N qualifier in the SELECT clause
   
    Dim rs As DAO.Recordset
    Dim SQL As String
    Dim ThisItem As String
    Dim FieldCounter As Long
   
    On Error GoTo ErrHandler
   
    ' Initialize to Null
   
    DConcat = Null
   
    ' Build up a query to grab the information needed for the concatenation
   
    SQL = "SELECT " & IIf(Distinct, "DISTINCT ", "") & _
           IIf(Limit > 0, "TOP " & Limit & " ", "") & _
            ConcatColumns & " " & _
       "FROM " & tbl & " " & _
      IIf(Criteria <> "", "WHERE " & Criteria & " ", "") & _
      IIf(Trim(OrderBy) <> "", "ORDER BY " & OrderBy, "")
     
    ' Open the recordset and loop through it:
    ' 1) Concatenate each column in each row of the recordset
    ' 2) Concatenate the resulting concatenated rows in the function's return value
   
    Set rs = CurrentDb.OpenRecordset(SQL)
    With rs
        Do Until .EOF
           
            ' Initialize variable for this row
           
            ThisItem = ""
           
            ' Concatenate columns on this row
           
            For FieldCounter = 0 To rs.Fields.Count - 1
                ThisItem = ThisItem & Delimiter2 & Nz(rs.Fields(FieldCounter).Value, "")
            Next
           
            ' Trim leading delimiter
           
            ThisItem = Mid(ThisItem, Len(Delimiter2) + 1)
           
            ' Concatenate row result to function return value
           
            DConcat = Nz(DConcat, "") & Delimiter1 & ThisItem
            .MoveNext
        Loop
        .Close
    End With
   
    ' Trim leading delimiter
   
    If Not IsNull(DConcat) Then DConcat = Mid(DConcat, Len(Delimiter1) + 1)
   
    GoTo Cleanup

ErrHandler:
   
    ' Error is most likely an invalid database object name, or bad syntax in the Criteria
   
    DConcat = CVErr(Err.Number)
   
Cleanup:
    Set rs = Nothing
   
End Function
0
 
LVL 92

Expert Comment

by:Patrick Matthews
ID: 34172792
Karen,

We're probably going to need a sample database to figure this one out.  Please be sure to purge it of confidential/sensitive information first.  Please post that file in the MDB format; many Experts here, myself included, do not always have an Access 2007/2010 instance available to them.  (I do have one, but not on my primary computer.)

Also, some tips that might make it easier for you in the future:

Any time your question relates to a query, always post the full SQL statement.  Without the full SQL statement, it is often difficult to discern what the end goal is
Posting a sample database always helps.  The sample need not be large, and you should take care to eliminate or obfuscate confidential/sensitive information before posting it, because the search engines will index the file
If the question involves anything having to do with VBA, be sure to post the source code for all of the procedures/functions you are asking about.  Such is the case here
If your question is related to something you found elsewhere, such as in a previous EE question, an EE article or blog post, or some other web page, include a URL to that material
If your question is at all related to previous questions you have asked (and indeed, you have asked a couple of questions about DConcat before), it is a good idea to go back to that older question, and use the 'ask a related question' link.  When you do that, EE automatically sends alerts to all Experts who subscribed to the original question

Cheers,

Patrick
0
 
LVL 45

Expert Comment

by:aikimark
ID: 34176379
0
 
LVL 1

Author Comment

by:ksilvoso
ID: 34177412
MatthewsPatrick
  Thanks for the helpful info.  My current question relates to these 2 previous questions:

http://www.experts-exchange.com/Microsoft/Development/MS_Access/Q_26490150.html
http://www.experts-exchange.com/Microsoft/Development/MS_Access/Q_26525770.html

I am putting together a sample database and will submit it with my next post.

0
 
LVL 1

Author Comment

by:ksilvoso
ID: 34179801
I have uploaded the database: ForEE.mdb
0
Enterprise Mobility and BYOD For Dummies

Like “For Dummies” books, you can read this in whatever order you choose and learn about mobility and BYOD; and how to put a competitive mobile infrastructure in place. Developed for SMBs and large enterprises alike, you will find helpful use cases, planning, and implementation.

 
LVL 1

Author Comment

by:ksilvoso
ID: 34179804
qryAncestorFamily is the relevant query.
0
 
LVL 1

Author Comment

by:ksilvoso
ID: 34183097
Sorry, the title of my question should say "sql code to sort dconcat"
0
 
LVL 1

Accepted Solution

by:
ksilvoso earned 0 total points
ID: 34183875
Well I changed my sql code to:

ChildrenSortedByAgeLinkedOnTextField: "Children:" & " " & Nz(DConcat("[Child First Name],[child date of birth], [Child Spouse Name2]","[qryancestorchildren]","[Ancestorcid] = " & [Ancestorcid] & "","; "," ",True," [child date of birth] ASC "),"")

I removed the single apostrophe in a couple of places and that took care of it.  Thanks anyway
0
 
LVL 92

Expert Comment

by:Patrick Matthews
ID: 34184019
Karen,

My apologies, the end of the week got extremely busy for me at work.

I am very, very pleased to see that you got this sorted out on your own :)

Cheers,

Patrick
0
 
LVL 1

Author Comment

by:ksilvoso
ID: 34209380
Thanks Patrick!
0
 
LVL 1

Author Closing Comment

by:ksilvoso
ID: 34216159
I googled the meaning of double apostrophe and single apostrophe in sql and asp code and tweaked the code until it worked.  Since my question was solved I didn't want to leave it open and have other people devoting their time to it so I accepted my own answer.
0

Featured Post

Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

I originally created this report in Crystal Reports 2008 where there is an option to underlay sections. I initially came across the problem in Access Reports where I was unable to run my border lines down through the entire page as I was using the P…
Introduction The Visual Basic for Applications (VBA) language is at the heart of every application that you write. It is your key to taking Access beyond the world of wizards into a world where anything is possible. This article introduces you to…
With Microsoft Access, learn how to specify relationships between tables and set various options on the relationship. Add the tables: Create the relationship: Decide if you’re going to set referential integrity: Decide if you want cascade upda…
Access reports are powerful and flexible. Learn how to create a query and then a grouped report using the wizard. Modify the report design after the wizard is done to make it look better. There will be another video to explain how to put the final p…

910 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

23 Experts available now in Live!

Get 1:1 Help Now