2014-02-18 86 views
0

我有一個查詢更新表記錄。查詢更新來自兩個不同表的記錄

UPDATE #TEMP 
    SET [fld_LastName] = CustomerProfile.fld_LastName 
    ,fld_FirstName = CustomerProfile.fld_FirstName 
    ,fld_BirthDate = CustomerProfile.fld_BirthDate 

FROM [DB_1].[dbo].[tbl_Customer] AS CustomerProfile --c 
WHERE CustomerProfile.fld_CustomerNo = #TEMP.fld_CustomerNo 

我想更新記錄時,客戶是不存在的:

[DB_1].[dbo].[tbl_Customer] 

我想仰望:

[DB_2].[dbo].[tbl_Customer] 

我如何能做到這一點在SQL查詢?

非常感謝。

回答

0

這應該爲你工作:

UPDATE B 
SET [fld_LastName] = CustomerProfile.fld_LastName 
,fld_FirstName = CustomerProfile.fld_FirstName 
,fld_BirthDate = CustomerProfile.fld_BirthDate 
FROM [DB_1].[dbo].[tbl_Customer] AS CustomerProfile INNER JOIN #TEMP B 
ON CustomerProfile.fld_CustomerNo = B.fld_CustomerNo 
WHERE B.[fld_LastName] IS NULL OR B.fld_FirstName IS NULL OR B.fld_BirthDate IS NULL 
0

你可以用一個更新做。事情是這樣的:

DECLARE @a TABLE (id INT, val INT) 
DECLARE @b TABLE (id INT, val INT) 
DECLARE @c TABLE (id INT, val INT) 

INSERT @a SELECT 1,NULL UNION SELECT 2,NULL UNION SELECT 3,30 
INSERT @b SELECT 1,10 
INSERT @c SELECT 1,20 UNION SELECT 2,20 

SELECT * FROM @a 

UPDATE @a 
    SET val = COALESCE(b.val,c.val,a.val) 
    FROM @a a 
     LEFT JOIN 
     @b b ON a.id=b.id 
     LEFT JOIN 
     @c c ON a.id=c.id 

SELECT * FROM @a 

這是假設你從DB_2喜歡NOT NULL值DB_1爲NULL值 - 如果這些字段甚至空。

UPDATE #TEMP 
    SET fld_LastName = COALESCE(b.fld_LastName,c.fld_LastName,a.fld_LastName) 
     ,fld_FirstName = COALESCE(b.fld_FirstName,c.fld_FirstName,a.fld_FirstName) 
     ,fld_BirthDate = COALESCE(b.fld_BirthDate,c.fld_BirthDate,a.fld_BirthDate) 
FROM #Temp a 
     LEFT JOIN 
     DB_1.dbo.tbl_Customer b ON a.fld_CustomerNo = b.fld_CustomerNo 
     LEFT JOIN 
     DB_2.dbo.tbl_Customer c ON a.fld_CustomerNo = c.fld_CustomerNo 
相關問題