我正在尝试更新一对多行,但最终结果是一对一更新。基本上,我有一个字符串列,我想连接从连接返回的所有结果(更新的顺序无关紧要)。
-- destination table
CREATE TABLE #TmpRes (SiteID bigint,ResString nvarchar(28) );
insert into #TmpRes (SiteID,ResString) values (1,'..'), (2,'..'), (3,'..');
-- join table (I only want to update SiteID #2)
CREATE TABLE #TmpData (DataNum bigint,DataStr nvarchar(28) );
insert into #TmpData (DataNum,DataStr) values (2,'CC'), (2,'BB'), (2,'AA');
-- this shows that the join is correct
select 'TJoin' TableName, *
FROM #TmpRes tr
join #TmpData td ON (tr.SiteID=td.DataNum) -- [1]
-- This update is only updating 1 row when it should be 3 rows
update #TmpRes
set ResString=tr.ResString + td.DataStr + tr.ResString
FROM #TmpRes tr
join #TmpData td ON (tr.SiteID=td.DataNum)
select '#TmpData' TableName, * from #TmpData --[2]
-- **expecting to see record 2 ResString to look like**
-- **..CC....BB....AA..**
select '#TmpRes' TableName, * from #TmpRes --[3]
上述SELECT
的结果:
1:
TJoin,2,..,2,CC
TJoin,2,..,2,BB
TJoin,2,..,2,AA
2:
TmpData,2,CC
TmpData,2,BB
TmpData,2,AA
3:
TmpRes,1,..
TmpRes,2,..CC..
TmpRes,3,..
我正在使用SQLServer 2014,但我确信任何SQL Server的结果都是一样的。
答案 0 :(得分:0)
- 希望看到记录2 ResString看起来像:
- ..CC .... BB .... AA ..
我认为您希望在连接其他表的行的特定值的基础上更新表,您可以使用FOR XML PATH
中的subquery
来执行此操作:
update tmr
set tmr.ResString=(
select tr.ResString + td.DataStr
FROM #TmpRes tr
join #TmpData td ON (tr.SiteID=td.DataNum)
where tr.SiteID=tmr.SiteID
For XML PATH ('')
)
FROM #TmpRes tmr
join #TmpData td ON (tmr.SiteID=td.DataNum)
检查结果:
select '#TmpRes' TableName, * from #TmpRes
TableName SiteID ResString
#TmpRes 1 ..
#TmpRes 2 ..CC..BB..AA
#TmpRes 3 ..