IF EXISTS (SELECT 1 FROM sys.objects WHERE object_id = OBJECT_ID('[dbo].[userfunc_392_fn_load_history]') AND type = 'P')
DROP PROCEDURE [dbo].[userfunc_392_fn_load_history]
GO
CREATE PROCEDURE userfunc_392_fn_load_history(@cmpid int,
@branchid int,
@userdpid int,
@useruid int,
@userotid int,
@usersecurity int,@identno varchar(20),@thisordid bigint) 

 as begin
    set nocount on ;
declare @maxordid bigint ,
        @hasInserted int  = -1  /*0：写入了明细，1：没有数据写入明细*/
        
set @maxordid  = @thisordid

select @maxordid  = max(ord_id) from order_29 with(nolock)
where ord_sfzhm = @identno 
and ord_id <> @thisordid

if(@maxordid <> @thisordid )
begin
    
    delete order_29_4 where ord2_ordid = @thisordid
    
    insert into order_29_4(ord2_ordid,ord2_tag,ord2_pgdh,ord2_pgsj,ord2_cuname,ord2_opinion)
    select @thisordid ordidx,4 tag,ord_no,ord2_pgsj,ord2_cuname,ord2_opinion
    from order_29 with(nolock),order_29_2 with(nolock)
    where ord2_ordid = @maxordid and ord_id = @maxordid
    union all
    select @thisordid ordidx,4 tag,ord_no,ord2_pgsj,ord2_cuname,ord2_opinion
    from order_29 with(nolock),order_29_4 with(nolock)
    where ord2_ordid = @maxordid  and ord_id = @maxordid
    
    set @hasInserted =@@ROWCOUNT

end
if(@@ROWCOUNT>0)
select 'YES' result
else 
    select 'NO' result
end