Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL Server 2008 - Select distinct names into variable

I need to send emails from SQL Server, to a constantly changing list of names. Luckily, the names are updated by users into a SQL Server table, so it should always be up to date.

I have already researched, and am hoping to use sp_SQLNotify to send the emails. (This is already set up and tested with actual lists of names - NOT yet with a variable).

Anyway, I need to populate a variable with the list of email addresses to send to.

In order to do this, I need the equivalent of:

SELECT DISTINCT [Email_Username] + '@my_email_suffix.com; '
INTO @VARIABLE
FROM My_Table

EXEC sp_SQLNotify @Variable 'My Header' 'My wall of text'

Is this possible, and what is the true syntax that I need to follow?

Please forgive my ignorance, but I struggle with some of the syntax.

Thanks, Craig.

===== UPDATED WITH ANSWER =====

Thanks to Aaron.

I used your code as the basis for a working solution.

For anyone trying to do this in future, the final result is:

-- Declare variable and populate with initial apostrophe
DECLARE @var VARCHAR(MAX) = '''';

-- Populate variable with all unique email user names
SELECT @var += x.email
FROM 
(
  SELECT DISTINCT [Email_Username] + '@my_email_suffix.com;'  AS email
  FROM dbo.[My_Table]
  WHERE [Email_Username] <> ''
) AS x 

-- Remove final semi-colon
SET @var = left(@var,len(@var)-1)

-- Add final apostrophe
SET @var = @var + ''''

-- Display result
SELECT @VAR;
like image 806
CraigA Avatar asked Feb 06 '13 17:02

CraigA


1 Answers

DECLARE @var VARCHAR(MAX) = '';

SELECT @var += x.email
FROM 
(
  SELECT DISTINCT (Email_Username + '@my_email_suffix.com;') as email
  FROM dbo.My_Table
) AS x;

SELECT @var;
like image 56
Aaron Bertrand Avatar answered Sep 28 '22 08:09

Aaron Bertrand