Concatenating during an update?

  • Hello everyone, I had a problem today that i thought would be quite simple to implement but didn't turn out to be as easy as i thought. I'll explain a similar scenario. So say you have a company table (CompanyId) & a Contacts table. The relation is 1 to many. The contacts table has an Email. I already had a temp table built up with a set of companies and i needed to concatenate x number of contact emails into one field (so you can send out one email with all the contacts in the to field) so this is what i tried which doesn't work:

    Declare @Temp Table (@CompanyId int,

    @Email VarChar(500)

    )

    Insert into @Temp(CompanyID)

    select distinct CompanyId from #Companies

    Update tmp

    Set Email = Coalesce(Email,'') + Coalesce(ct.Email,'') + ';'

    From @Temp tmp

    Inner Join TblContacts ct

    on tmp.CompanyId = ct.CompanyId

    A coworker has a solution that he sent me that uses xml (can't really explain it because i haven't had time to review it). So my question is is there another straight forward solution to this problem without using a cursors or xml?

    thanks...

  • There's a possibility, but you must be careful when you apply it. Check the following article:

    http://www.sqlservercentral.com/articles/T-SQL/68467/

    Even if you can't use it, it's a great article. 🙂

    Luis C.
    General Disclaimer:
    Are you seriously taking the advice and code from someone from the internet without testing it? Do you at least understand it? Or can it easily kill your server?

    How to post data/code on a forum to get the best help: Option 1 / Option 2

Viewing 2 posts - 1 through 1 (of 1 total)

You must be logged in to reply to this topic. Login to reply