試試這個:
DECLARE @list1 AS TABLE (Emp_Num INT, Emp_Name VARCHAR(100), Emp_Salary MONEY)
DECLARE @list2 AS TABLE (Emp_Num INT, Emp_Name VARCHAR(100), Emp_Age INT)
INSERT INTO @list1
SELECT 1, 'TOM', 5000
UNION ALL SELECT 2, 'BRIAN', 6000
UNION ALL SELECT 3, 'RAM', 8000
UNION ALL SELECT 4, 'DINESH', 8000
INSERT INTO @list2
SELECT 1, 'TOM', 20
UNION ALL SELECT 2, 'BRIAN', 40
UNION ALL SELECT 3, 'RAM', 60
UNION ALL SELECT 5, 'SARATH', 90
;WITH list AS (
SELECT Emp_Num, Emp_Name FROM @list1
UNION
SELECT Emp_Num, Emp_Name FROM @list2
)
SELECT L0.Emp_Num, L0.Emp_Name, EMP_SALARY = L1.Emp_Salary, EMP_AGE = L2.Emp_Age
FROM list AS L0
LEFT OUTER JOIN @list1 L1 ON L1.Emp_Num = L0.Emp_Num
LEFT OUTER JOIN @list2 L2 ON L2.Emp_Num = L0.Emp_Num
-- OUTPUT
Emp_Num Emp_Name EMP_SALARY EMP_AGE
1 TOM 5000.00 20
2 BRIAN 6000.00 40
3 RAM 8000.00 60
4 DINESH 8000.00 NULL
5 SARATH NULL 90
如果tb1.EMP_NUM和tb1.emp_name具有實際空值,那麼我不應該填充tb2.emp_num&tb2.emp_name – user1050619
@ user1050619你什麼計劃在TB2中使用TB1中沒有匹配的EMP_NUM的行?如果這種情況不會發生,那麼你應該使用'LEFT OUTER JOIN'而不是'FULL OUTER JOIN'。否則,您至少要保留EMP_NUM的'COALESCE',然後可以在EMP_NAME中使用'CASE'語句來檢查'TB1.EMP_NUM IS NULL'。 –