Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does this SQL script work as it does?

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?

like image 632
Chris Burgess Avatar asked Nov 10 '08 22:11

Chris Burgess


People also ask

What does this SQL script mean?

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.

What does with AS do in SQL?

The AS command is used to rename a column or table with an alias. An alias only exists for the duration of the query.

What does script table as do in SQL?

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.

What is the difference between SQL query and SQL script?

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.


2 Answers

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.

like image 145
Joel Coehoorn Avatar answered Oct 21 '22 23:10

Joel Coehoorn


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]".

like image 24
bdumitriu Avatar answered Oct 21 '22 22:10

bdumitriu