我有两个表:表A保存主产品数据,表B保存子产品数据。我想更新表A,使其在表B中只有一个不同的值时,保持表B中相同列的相同值。如果非重复计数大于1,我想用逗号将各列连接起来。除键列名称外,这些表具有相同的列。
是否可以编写将匹配所有列并处理合并/串联的动态SQL?
下面的例子:
表A
ID | 颜色| 地点 ____ | ______ | _____________ 1 | | 2 | | 3 | | 4 | |
表B
child_ID | parent_id | 颜色| 地点 __________ | ___________ | ________ | _________ 1 | 1 | 白色| 房子 2 | 2 | 红色| 车库 3 | 2 | 白色| 车库 4 | 3 | 蓝色| 房子
表A如下所示:
ID | 颜色| 地点 ____ | ___________ | _______________ 1 | 白色| 房子 2 | 红色,白色| 车库 3 | 白色| 房子
检查一下…
IF OBJECT_ID('TableA') IS NOT NULL DROP TABLE TableA IF OBJECT_ID('TableB') IS NOT NULL DROP TABLE TableB CREATE TABLE TableA (ID INT, Color VARCHAR(max), Location VARCHAR(max), Class VARCHAR(max)) CREATE TABLE TableB (child_ID INT, parent_ID INT, Color VARCHAR(10), Location VARCHAR(10), Class VARCHAR(10)) INSERT INTO TableB SELECT 1,1,'white','house' ,'I' UNION SELECT 2,2,'red' ,'garage' ,'II' UNION SELECT 3,2,'white','garage' ,'I' UNION SELECT 4,3,'blue' ,'house' ,'IV' UNION SELECT 5,3,'blue' ,'garage' ,'I' UNION SELECT 6,3,'white','garage' ,'I' UNION SELECT 7,3,'gray' ,'garage' ,'I' UNION SELECT 8,2,'gray' ,'house' ,'IV' SELECT * FROM TableB DECLARE @cmd VARCHAR(max); SET @cmd = 'INSERT INTO TableA SELECT ID = b.parent_id ' SELECT @cmd = @cmd + ' , ['+COLUMN_NAME+'] = STUFF( ( SELECT '', '' +'+COLUMN_NAME+' FROM TableB WHERE parent_id = b.parent_id GROUP BY '+COLUMN_NAME+' FOR XML PATH('''') ) , 1, 2, '''' )' FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME='TableB' AND COLUMN_NAME NOT IN ('child_ID', 'parent_id') SELECT @cmd = @cmd + ' FROM TableB AS b GROUP BY b.parent_id' EXEC(@cmd) SELECT * FROM TableA /* -- OUTPUT ID | Color | Location | Class --------------------------------------------------- 1 | white | house | I 2 | gray, red, white | garage, house | I, II, IV 3 | blue, gray, white | garage, house | I, IV */