Technical Article

Create string from table

,

I needed something that would return a list of email addresses from a particular column in a table, based on a condition in a joined table.

The above script will work with both the COALESCE or the ISNULL function. For both the datatype may need to be adapted (as shown here). The result of ISNULL() always takes on the datatype of the first parameter (regardless of whether it is NULL or NOT NULL). COALESCE works more like a CASE expression, which returns a single datatype depending on precendence and accommodating all possible outcomes.

The difference between the first and second example is purely to illustrate the difference in the formatting of the string.

-- Example 1
DECLARE @email VARCHAR(250)
BEGIN
SELECT @email = COALESCE(@email + ', ', '') + (CAST(columnC AS varchar(30)))
FROM  db.table1 INNER JOIN db.table2 ON db.table1.columnA = db.table2.columnA
WHERE db.table1.columnb = 'email'
SELECT @email
END
GO

-- Example 2
DECLARE @email VARCHAR(250)
BEGIN
SELECT @email = COALESCE(@email + ', ', '') + '''' + (CAST(columnC AS varchar(30))) + ''''
FROM  db.table1 INNER JOIN db.table2 ON db.table1.columnA = db.table2.columnA
WHERE db.table1.columnb = 'email'
SET @email = '[' + @email + ']'
SELECT @email
END
GO

Rate

1 (1)

You rated this post out of 5. Change rating

Share

Share

Rate

1 (1)

You rated this post out of 5. Change rating