我有一个更新表记录的查询。
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 :(得分: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
答案 1 :(得分: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_1中从DB_2到NULL值的NOT 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