我正在尝试使用UPDATE和INNER JOIN的东西查询而没有成功。 我需要将查询结果填充到一个列/行中,并使用该结果更新另一个表。
我目前的代码就是这个。
Update t1
SET t1.col1 = t2.ordernotes
FROM db.dbo.table1 t1
INNER JOIN
STUFF((
(Select order_no, Notes As ordernotes
FROM db.dbo.table2
GROUP BY order_no
ORDER BY TimeStamp
FOR XML PATH('')
),1,1,'')
As t2
ON t2.order_no = t1.order_no
内部联接中的查询返回以下结果
Order_no | OrderNotes
1234 | Note 1
1234 | Note 2
1234 | Note 3
所需的结果是这个,然后更新到表1
Order_no | OrderNotes
1234 | Note 1, Note 2, Note 3
答案 0 :(得分:2)
一种方法使用cross apply
:
Update t1
SET t1.col1 = t2.ordernotes
FROM db.dbo.table1 t1 CROSS APPLY
(SELECT STUFF((SELECT ', ' + t1.Notes
FROM db.dbo.table2
WHERE t2.order_no = t1.order_no
ORDER BY t2.TimeStamp
FOR XML PATH('')
), 1, 2, ''
) as ordernotes
) t2;
但是,最好养成使用type
进行字符串连接的习惯:
Update t1
SET t1.col1 = t2.ordernotes
FROM db.dbo.table1 t1 CROSS APPLY
(SELECT STUFF((SELECT ', ' + t1.Notes
FROM db.dbo.table2
WHERE t2.order_no = t1.order_no
ORDER BY t2.TimeStamp
FOR XML PATH(''), TYPE
).VALUE('.', 'nvarchar(max)'
), 1, 2, ''
) as ordernotes
) t2;