6

I'm pulling email address records from a table in SQL Server 2005, and want to build a single string to use as the @recipients list with sp_send_dbmail. The table has a field called EmailAddress and there are 10 records in the table.

I'm doing this:

DECLARE @email VARCHAR(MAX)
SELECT
    @email = ISNULL(@email + '; ', '') + EmailAddress
FROM
    accounts

Now @email has a semi-delimited list of 10 email address from the accounts table.

My questions is why/how does this work? Why doesn't @email only have the last email address in the table?

ConcernedOfTunbridgeWells
  • 64,444
  • 15
  • 143
  • 197
Chris Burgess
  • 5,787
  • 13
  • 54
  • 69

4 Answers4

5

Because for each row you concatentate the current value of @email with the next result in EmailAddress. String concatenation is just like calling a function, in that it must evaluate the result for each row in sequence.

Joel Coehoorn
  • 399,467
  • 113
  • 570
  • 794
4

Say you have 3 addresses:

a@b.c
b@b.c
c@b.c

For the first row, @email is NULL, so it becomes "" + "a@b.c", so "a@b.c".

For the second row, @email becomes "a@b.c" + "; " + "b@b.c", so "a@b.c; b@b.c".

For the last row, @email becomes "a@b.c; b@b.c" + "; " + "c@b.c", so "a@b.c; b@b.c; c@b.c".

bdumitriu
  • 1,313
  • 9
  • 12
2

Because the concatenation expression is evaluated once per row.

mercutio
  • 22,151
  • 10
  • 36
  • 37
1

Your SELECT isn't selecting rows - for display - it's repeatedly concatenating an expression to the same variable. So at the end, all you have left to show is the variable.

Presumably you find that out with another line in the batch file, e.g. "SELECT @email"

Think:

result = "" + name1
result = result + name2
result = result + name3
etc.

Possibly you're thinking that SELECT variable = expression is a combination assignment and SELECT; but it's really just an assignment. In any case, @email isn't reinitialized for each row.

dkretz
  • 37,399
  • 13
  • 80
  • 138