Sql 仅在一个ID上更新

Sql 仅在一个ID上更新,sql,sql-server,Sql,Sql Server,我想执行update语句,但此update查询必须只更新一行。我需要知道id或密钥只出现一次 update td set td.t_ID = d.Document_ID from #t_documents td join document d with (nolock) on d.D_header = td.t_header_ID and d.D_sequence = td.t_D_sequence where count(distinct d.Document_ID) = 1 我如何执行

我想执行update语句,但此update查询必须只更新一行。我需要知道id或密钥只出现一次

update td
set td.t_ID = d.Document_ID 
from #t_documents td
join document d with (nolock)
on d.D_header = td.t_header_ID
and d.D_sequence = td.t_D_sequence 
where count(distinct d.Document_ID) = 1

我如何执行此查询,以检查更新是否只执行了一次

不确定这是否是您要查找的内容,但试一试:

IF (
    SELECT count(DISTINCT d.Document_ID)
    from #t_documents td
    join document d with (nolock)
    on d.D_header = td.t_header_ID
    and d.D_sequence = td.t_D_sequence) = 1
BEGIN
    update td
    set td.t_ID = d.Document_ID 
    from #t_documents td
    join document d with (nolock)
    on d.D_header = td.t_header_ID
    and d.D_sequence = td.t_D_sequence 
END
或者正如Stephen所指出的,subqueryhaven没有对此进行测试:

update td
set td.t_ID = d.Document_ID 
from #t_documents td
join document d with (nolock)
on d.D_header = td.t_header_ID
and d.D_sequence = td.t_D_sequence 
where (
    SELECT count(DISTINCT d.Document_ID)
    from #t_documents td
    join document d with (nolock)
    on d.D_header = td.t_header_ID
    and d.D_sequence = td.t_D_sequence) = 1

添加示例数据和预期结果。必须使用where子句上的子查询。其中1=选择count from where id=td.id…只是指出第一个选项将无法按预期工作。问题是我不确定这个问题中的预期内容,但您可能是对的第二个选项比我预期的要多。感谢you@sarikaya,您是否使用第二个脚本获得了正确的更新,或者必须对其进行修改?