【发布时间】:2016-11-05 06:13:51
【问题描述】:
CREATE TABLE table1
(
num INT,
val VARCHAR(100)
);
INSERT INTO table1
VALUES (1, 'test1'), (2, 'test2'), (1, 'test3'), (1, 'test4')
CREATE TABLE table2
(
num INT,
concatenation VARCHAR(1000)
)
INSERT INTO table2
SELECT num,
Substring((SELECT DISTINCT ',' + T2.val
FROM table1 T2
WHERE T1.num = T2.num
FOR XML PATH('')), 2, 1000000)
FROM table1 T1
GROUP BY num
现在我使用查询更新了第一条记录
UPDATE table2
SET concatenation = 'test1,test25,test4'
WHERE num = 1
现在在table1中插入更多记录
INSERT INTO table1(num,val)
VALUES (3,'test5'),(1,'test6')(1,'test1')
现在我想用不重复的更新行更新table2 记录。在这里,如果文本不存在,我想连接,如果存在重复则避免。
预期结果:我对 table2 结果的更新应该得到如下预期结果
select * from table2
输出:
Num concatenation
-----------------------------------
1 test1,test25,test3,test4,test6
2 test2
3 test5
【问题讨论】:
-
那么,
num=1的预期结果将是test1,test25,test4,test6? -
嗨@NEER我按照你的要求添加了预期的结果。请帮帮我。
标签: sql sql-server sql-server-2008 sql-server-2012 sql-server-2008-r2