IF EXISTS (SELECT 1 FROM sys.objects WHERE object_id = OBJECT_ID('[dbo].[userfunc_562_dwh]') AND type = 'P')
DROP PROCEDURE [dbo].[userfunc_562_dwh]
GO
CREATE PROCEDURE userfunc_562_dwh(@cmpid int,   @branchid int,  @userdpid int,  @useruid int,   @userotid int,  @usersecurity int,@ctgid int,@ctgid2 int,@objid bigint,@hdlx varchar(100))
as
begin



    declare @ygcount int
    declare @dp_code1 varchar(20)
    select @dp_code1 = dp_code from mps_depart where dp_id = @userdpid
    select @ygcount = COUNT(ord2_id) 
    from order_241 as m inner join order_241_2 as d
    on m.ord_id = d.ord2_ordid 
    where m.ord_status = '已分配' and m.ord_whlx = '允许拨打' and d.ord2_sfbd = '否'
    and d.ord2_mdbh = @dp_code1
    and  ord2_cuid = @useruid and (@hdlx = '全部' or ord_hdlx = @hdlx)

    if ( @ygcount > 0 )
    begin 
          select top 100 ord2_id,ord2_ordid,ord2_hm,ord2_xm,ord2_zzftc,ord2_cuid,ord2_creator,ord_yxhd,ord_hdlx
          from order_241 as m WITH(NOLOCK) inner join order_241_2 as d WITH(NOLOCK)
          on m.ord_id = d.ord2_ordid 
          where m.ord_status = '已分配' and m.ord_whlx = '允许拨打' and d.ord2_sfbd = '否'
          and d.ord2_mdbh = @dp_code1
          and ord2_cuid = @useruid and (@hdlx = '全部' or ord_hdlx = @hdlx)
    end
    else
    begin
          select top 100 ord2_id,ord2_ordid,ord2_hm,ord2_xm,ord2_zzftc,ord2_cuid,ord2_creator,ord_yxhd,ord_hdlx
          from order_241 as m WITH(NOLOCK) inner join order_241_2 as d WITH(NOLOCK)
          on m.ord_id = d.ord2_ordid 
          where m.ord_status = '已分配' and m.ord_whlx = '允许拨打' and d.ord2_sfbd = '否'
          and d.ord2_mdbh = @dp_code1
          and ord2_cuid = 0 and (@hdlx = '全部' or ord_hdlx = @hdlx)
    end


end