我有一个使用新数据更新现有记录所需的存储过程,但它不能“覆盖”任何现有数据。
例如,我们可能有三个字段:
FirstName | LastName | PhoneNumber
调用上面的'TableX'。
在一个非常简单的更新中,这看起来像这样:
Update TableX
set FirstName = [TableY.FirstName]
,LastName = [TableY.LastName]
,PhoneNumber = [TableY.PhoneNumer]
etc.....
但是我要求每列只有更新(来自TableY),如果它是空的。
答案 0 :(得分:4)
Update TableX
set FirstName = ISNULL(FirstName, [TableY.FirstName])
,LastName = ISNULL(LastNastName, [TableY.LastName])
,PhoneNumber = ISNULL(PhoneNumber, [TableY.PhoneNumer])
...
如果'empty'不代表NULL,那么
Update TableX
set FirstName = case FirstName when "" then [TableY.FirstName] else FirstName end
,LastName = case LastName when "" then [TableY.LastName]) else LastName end
,PhoneNumber = case PhoneNumber when "" then [TableY.PhoneNumer] else PhoneNumber end
答案 1 :(得分:1)
您需要使用when then来执行此操作。
UPDATE [AdventureWorks_DB].[dbo].[activities]
SET [FirstName ] = case when FirstName is null then 'pass First Name'
else [FirstName ]
end,
LastName = case when LastName is null then 'pass Last Name'
else LastName
end,
PhoneNumber = case when PhoneNumber is null then 'pass PhoneNumber'
else PhoneNumber
end
答案 2 :(得分:0)
update
TableX
set
FirstName = (case when FirstName = null then @firstname else FirstName end)
where
Id=1
答案 3 :(得分:0)
因为更新在逻辑上是删除,所以插入对使用COALESCE
模式没有任何害处,尽管最好不要检查所有NULL参数值,例如
UPDATE TableX
SET FirstName = COALESCE(@FirstName, FirstName),
LastName = COALESCE(@LastName, LastName),
PhoneNumber = COALESCE(@PhoneNumber, PhoneNumer)
WHERE COALESCE(@FirstName, @LastName, @PhoneNumber) IS NOT NULL
AND person_X_ID = @person_X_ID;