我有两个表,如下所示,尝试使用merge指定结果。有可能吗?
表1 :
ConID Table1ID Q1A Q2A Q3A Active
------------------------------------------------
100 1 2 Test 1 1
101 2 3 Test2 1 1
102 3 4 Test3 1 1
104 4 5 Test4 1 1
105 5 5 Test5 1 0
还存在第5行的数据,在这种情况下它是非活动的而不是更新该行,我需要添加具有相同细节但是活动行的新行。有关如何更新脚本的任何建议。 table1存在标识列,因此数据不会重复。
在查看现有记录时,比较table2中的数据并更新表1中的数据。
表2 :
Table1ID E1 E2 E3
----------------------------------------
1 2 TestData1 1
2 3 TestData2 1
3 4 TestData3 1
5 5 TestData5 1
6 7 TestData6 0
结果:
ConID Table1ID Q1A Q2A Q3A Active
-----------------------------------------
100 1 2 Test 1 1 -- Rows with Id 1,2,3 already exists in table 1 dont do anything
101 2 3 Test2 1 1
102 3 4 Test3 1 1
104 4 5 Test4 1 0 -- Rows with Id 4 exists in table 1 but not in table 2 update it to inactive
105 5 5 Test5 1 0
106 5 5 TestData5 1 1 -- Rows with Id 5,6 does not exist in table 1 so insert it
107 6 7 TestData6 0 1
答案 0 :(得分:0)
我不知道你是如何生成Test6的,因为它没有在你的任何表中找到(只有表2中的TestData6),但我猜它与表1相同,Q1 = E1和Q2 = E2和等等。
由于我的脚本中没有计算列,因此只需输入即可生成ConID 107。
-- Declare Table Variables. The result will be in table result. You can then merge it into table 1 or do whatever you want
DECLARE @tab1 TABLE ( ConId int, Table1ID int, Q1A int, Q2A nvarchar(100), Q3A int, Active int )
DECLARE @tab2 TABLE ( Table1ID int, E1 int, E2 nvarchar(100), E3 int )
DECLARE @result TABLE ( ConId int, Table1ID int, Q1A int, Q2A nvarchar(100), Q3A int, Active int )
INSERT INTO @tab1 VALUES ( 100, 1, 2, 'Test', 1, 1 )
INSERT INTO @tab1 VALUES ( 101, 2, 3, 'Test2', 1, 1 )
INSERT INTO @tab1 VALUES ( 102, 3, 4, 'Test3', 1, 1 )
INSERT INTO @tab1 VALUES ( 104, 4, 5, 'Test4', 1, 1 )
INSERT INTO @tab1 VALUES ( 105, 5, 5, 'Test5', 1, 0 )
INSERT INTO @tab2 VALUES ( 1, 2, 'TestData1', 1 )
INSERT INTO @tab2 VALUES ( 2, 3, 'TestData2', 1 )
INSERT INTO @tab2 VALUES ( 3, 4, 'TestData3', 1 )
INSERT INTO @tab2 VALUES ( 5, 5, 'TestData5', 1 )
INSERT INTO @tab2 VALUES ( 6, 7, 'TestData6', 0 )
-- Insert the rows from tab1 and tab2 as requested with matching Active State
INSERT INTO @result
SELECT ConId, t1.Table1ID, Q1A, Q2A, Q3A, case WHEN t2.E3 IS NULL THEN '0' ELSE (case WHEN t1.Active = 0 THEN '0' ELSE '1' END) END
FROM @tab1 t1
LEFT OUTER JOIN @tab2 t2
ON t1.Table1ID = t2.Table1ID
-- Duplicate Row with state active if it is inactive in table 1 and found in table 2
INSERT INTO @result
SELECT ConId, t1.Table1ID, Q1A, Q2A, Q3A, 1
FROM @tab1 t1
LEFT OUTER JOIN @tab2 t2
ON t1.Table1ID = t2.Table1ID
WHERE t1.Active = 0
AND t2.E1 is NOT NULL
-- Insert Rows only existing in Table 2 but not in table 1 with corrected data
INSERT INTO @result
SELECT 107, t2.Table1ID, E1, REPLACE(E2, 'Data', ''), E3, 1
FROM @tab1 t1
RIGHT OUTER JOIN @tab2 t2
ON t1.Table1ID = t2.Table1ID
WHERE t1.Q1A is NULL
SELECT *
FROM @result
ORDER BY ConId
此脚本导致:
ConId Table1ID Q1A Q2A Q3A Active
100 1 2 Test 1 1
101 2 3 Test2 1 1
102 3 4 Test3 1 1
104 4 5 Test4 1 0
105 5 5 Test5 1 0
105 5 5 Test5 1 1
107 6 7 Test6 0 1