0

可能重复:
仅当一行受到影响时如何执行更新?

我在 SQL Server 2005 中有一个更新查询

update custom_graphics_files 
set actual_file_Name = @CorrectName 
where actual_file_Name = @FileName

现在如果有多个actual_file_name,我想跳过更新查询,

4

3 回答 3

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;
于 2013-02-04T14:11:29.687 回答
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
于 2013-02-04T14:27:02.053 回答
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.

于 2013-02-04T14:20:35.247 回答