Results 1 to 5 of 5

Thread: SELECT DISTINCT in DECLARE

  1. #1
    Join Date
    Jul 2005
    Posts
    3

    SELECT DISTINCT in DECLARE

    Hi


    I try to use this code in query analyzer

    DECLARE @SendTo VarChar(4000)
    SET @SendTo = ''
    SELECT DISTINCT @SendTo = @SendTo + UserEmail + ';' FROM dbo.tbl_AccountInfo WHERE (UserEmail <> '')
    PRINT @SendTo

    The purpose of this code is to build up a ; seperated string of email adresses that I can use sending mail from SQL server.

    It works but it only give me one record (should give me 130 records) , but if I remove the DISTINCT part it give me all records, duplicates too. Does anyone know why and how can I get this to work? Or maybe do it in another way?


    Best regards

  2. #2
    Join Date
    Nov 2002
    Location
    New Jersey, USA
    Posts
    3,932
    DECLARE @SendTo VarChar(4000)
    SET @SendTo = ''

    SELECT @SendTo = @SendTo + a.UserEmail + ';'
    FROM
    (
    SELECT DISTINCT UserEmail
    FROM dbo.tbl_AccountInfo
    WHERE (UserEmail <> '')) as a
    PRINT @SendTo

  3. #3
    Join Date
    Jul 2005
    Posts
    3
    Hi skhanal


    Thanks a lot! That worked perfect, one thing though. The generated string ends up with a ;. Is there a way I can remove that to?


    Best Regards

  4. #4
    Join Date
    Feb 2003
    Posts
    1,048
    DECLARE @SendTo VarChar(4000)

    SELECT @SendTo = IsNull(@SendTo + ';', '') + a.UserEmail
    FROM
    (
    SELECT DISTINCT UserEmail
    FROM dbo.tbl_AccountInfo
    WHERE (UserEmail <> '')) as a

    PRINT @SendTo

  5. #5
    Join Date
    Jul 2005
    Posts
    3
    Hi


    Worked like a charm, Thanks a lot!

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •