简体   繁体   中英

concatenate indeterminate numbers of strings in SQL Server 2008

I need to send out an email in bulk, with the email containing each course associated with that particular user's email. The following query will return a list of all courses and users associated with them.

select (cm.course_id + ': '+ cm.course_name) as course,
u.lastname, u.firstname, u.email from course_users cu
join users u on u.pk1 = cu.users_pk1
join course_main cm on cm.pk1 = cu.crsmain_pk1

The trouble is that for the Mail Merge to work properly, I need each user listed only once, and all associated courses in a single (delimited) cell for that row.

Any help is appreciated!

EDIT: Removing text about the CONCAT() function because it's just distracting.

You can use SQL Server's XML extensions to concatenate rows:

SELECT  Course = STUFF((SELECT  ';' + cm.course_id + ': '+ cm.course_name
                        FROM    course_users cu
                                INNER JOIN course_main cm
                                    ON cm.pk1 = cu.crsmain_pk1
                        WHERE   u.pk1 = cu.users_pk1
                        FOR XML PATH(''), TYPE
                        ).value('.', 'NVARCHAR(MAX)'), 1, 1, ''),
        u.lastname, 
        u.firstname, 
        u.email
FROM    users u;

For a more detailed explanation of how this works see this answer .

Example on SQL Fiddle

EDIT

To limit this to only users on a course you can move the logic to within an APPLY, then check the result is not null:

SELECT  Course = STUFF(c.course.value('.', 'NVARCHAR(MAX)'), 1, 1, ''),
        u.lastname, 
        u.firstname, 
        u.email
FROM    users u
        CROSS APPLY
        (   SELECT  ';' + cm.course_id + ': '+ cm.course_name
            FROM    course_users cu
                    INNER JOIN course_main cm
                        ON cm.pk1 = cu.crsmain_pk1
            WHERE   u.pk1 = cu.users_pk1
            FOR XML PATH(''), TYPE
        ) c (course)
WHERE   c.course IS NOT NULL;

or add an exists clause:

SELECT  Course = STUFF((SELECT  ';' + cm.course_id + ': '+ cm.course_name
                        FROM    course_users cu
                                INNER JOIN course_main cm
                                    ON cm.pk1 = cu.crsmain_pk1
                        WHERE   u.pk1 = cu.users_pk1
                        FOR XML PATH(''), TYPE
                        ).value('.', 'NVARCHAR(MAX)'), 1, 1, ''),
        u.lastname, 
        u.firstname, 
        u.email
FROM    users u
WHERE   EXISTS (SELECT 1 FROM course_users cu WHERE u.pk1 = cu.users_pk1);

Examples of both on SQL Fiddle

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM