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?
What is SQL Scripts? A SQL script is a set of SQL commands saved as a file in SQL Scripts. A SQL script can contain one or more SQL statements or PL/SQL blocks. You can use SQL Scripts to create, edit, view, run, and delete script files.
The AS command is used to rename a column or table with an alias. An alias only exists for the duration of the query.
Script tables Use this option to either create the table or drop and create the table. You can also use this option to script the T-SQL associated with modifying the table. An example is to insert into it or update to it.
Unlike a SQL query, which is a single statement or entity, a SQL script is a collection of two or more SQL statements. Its purpose is to group related statements together to accomplish a more complex goal.
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.
Say you have 3 addresses:
[email protected]
[email protected]
[email protected]
For the first row, @email
is NULL
, so it becomes "" + "[email protected]"
, so "[email protected]"
.
For the second row, @email
becomes "[email protected]" + "; " + "[email protected]"
, so "[email protected]; [email protected]"
.
For the last row, @email
becomes "[email protected]; [email protected]" + "; " + "[email protected]"
, so "[email protected]; [email protected]; [email protected]"
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With