可能重复:
How to execute an UPDATE only if one row would be affected?
我在SQL Server 2005中有一个更新查询
update custom_graphics_files
set actual_file_Name = @CorrectName
where actual_file_Name = @FileName
现在,如果有多个actual_file_name
,我想跳过更新查询
答案 0 :(得分:1)
update t
set t.actual_file_Name = @CorrectName
FROM custom_graphics_files t
INNER JOIN
(
SELECT actual_file_Name, COUNT(*) TheCount
FROM custom_graphics_files
GROUP BY actual_file_Name
) t2 ON t.actual_file_Name = t2.actual_file_Name AND TheCount = 1
where t.actual_file_Name = @FileName;
答案 1 :(得分:0)
我喜欢为此目的使用窗口函数:
with toupdate as (
select cgf.*, COUNT(*) over (PARTITION by actual_file_name) as ActCnt
from custom_graphics_files
)
update toupdate
set actual_file_Name = @CorrectName
where actual_file_Name = @FileName and ActCnt = 1
在大型桌面上,这可能不是最有效的解决方案,具体取决于actual_file_Name = @FileName
的选择性。
答案 2 :(得分:0)
这是您可以获得的最“可读”的查询:
update custom_graphics_files
set actual_file_Name = @CorrectName
where actual_file_Name = @FileName
and (select count(1) from custom_graphics_files where actual_file_Name = @FileName) = 1