问题
I have a table which contains lots of NULLs in the email field. What I need to do is updating all the NULL rows. For every NULL row, I need to execture a stored procedure which basically gets all the emails related to that user's ID. Therefore, for every NULL row, this stored procedure is called and all the email fields found within this stored procedure need to be concatenated together and inserted in place of the NULL email field from the other table.
Anyone knows how to implement this in TSQL?
Many thanks in advance
EDIT:
I have found this code:
WITH Ranked ( CategoryId, rnk, ProductName )
AS ( SELECT CategoryId,
ROW_NUMBER() OVER( PARTITION BY CategoryId ORDER BY CategoryId ),
CAST( ProductName AS VARCHAR(8000) )
FROM Northwind..Products),
AnchorRanked ( CategoryId, rnk, ProductName )
AS ( SELECT CategoryId, rnk, ProductName
FROM Ranked
WHERE rnk = 1 ),
RecurRanked ( CategoryId, rnk, ProductName )
AS ( SELECT CategoryId, rnk, ProductName
FROM AnchorRanked
UNION ALL
SELECT Ranked.CategoryId, Ranked.rnk,
RecurRanked.ProductName + ', ' + Ranked.ProductName
FROM Ranked
INNER JOIN RecurRanked
ON Ranked.CategoryId = RecurRanked.CategoryId
AND Ranked.rnk = RecurRanked.rnk + 1 )
SELECT CategoryId, MAX( ProductName )
FROM RecurRanked
GROUP BY CategoryId;
However I can't get it to work in my case.
Basically, instead of using the stored procedure I can simply use the select statement to get one row with all the necessary emails. What I essentially need to do is to concatenate these returned emails into one row.
回答1:
From this: http://geekswithblogs.net/nagendraprasad/archive/2009/03/13/convert-multiple-rows-into-one-row---sql-server.aspx
Convert multiple rows into one row - SQL Server As I need to send email to many people, i need to convert multiple emails into a single row delimited by semi-colon(;), i had lots of solutions, but which is an old type of solution which needs more lines of code. As i want to use one or two line code which would resolve, i found three methods for my solution which is very simple.
Method 1:
DECLARE @str varchar(4000)
SET @str = (SELECT CONTACT_EMAIL + ';' FROM table FOR XML PATH(''))
SET @str = SUBSTRING(@str,1,LEN(@str)-1)
SELECT @str
Method 2:
DECLARE @str varchar(4000)
SELECT @str = COALESCE(@str + ';', '') + CONTACT_EMAIL FROM table
SELECT @str
Method 3:
DECLARE @str varchar(4000)
SELECT DISTINCT STUFF( (SELECT CONTACT_EMAIL + ';' from table FOR XML PATH('')),1,1,'')
SELECT @str
Multiple rows returned:
CONTACT_EMAIL
abc1@domain.com
abc2@domain.com
abc3@domain.com
3 row(s) affected.
After executing one of the methods, i got the result as
CONTACT_EMAIL
abc1@domain.com;abc2@domain.com;abc3@domain.com;
1 row(s) affected.
来源:https://stackoverflow.com/questions/9395444/concatenating-rows-from-a-stored-procedure-onto-another-table-in-tsql