IF EXISTS (SELECT 1 FROM sys.objects WHERE object_id = OBJECT_ID('[dbo].[proj_loaduserwithConditions]') AND type = 'P')
DROP PROCEDURE [dbo].[proj_loaduserwithConditions]
GO

CREATE proc [dbo].[proj_loaduserwithConditions] (
@conditions nvarchar(1000),
@ordid  bigint
) 
as
begin

set nocount on ;
declare @singleConditionname nvarchar(1000),
@singleConditiontext nvarchar(1000)
declare @sqlrun varchar(max) = ''

while(@conditions>'')
begin
set @singleConditionname = ''
if((select (charindex(',',@conditions)-1)) = -1)
begin
select @singleConditionname = @conditions
select @singleConditiontext =bm_text2  from mps_code where bm_text= @singleConditionname and bm_ctg='cu_level'
set @sqlrun= @sqlrun + @singleConditiontext
set @conditions=''
end
else
begin
select @singleConditionname = substring(@conditions,1,(charindex(',',@conditions)-1))
select @singleConditiontext =bm_text2 from mps_code where bm_text= @singleConditionname and bm_ctg='cu_level'
set @sqlrun = @sqlrun + @singleConditiontext+ ' union '
select @conditions = substring(@conditions,(charindex(',',@conditions)+1),len(@conditions))
end
end

if object_id('tempdb.dbo.#TBB') is not null 
drop table #TBB

create table #TBB(cuid bigint,tbb_zj nvarchar(800))

set @sqlrun = 'insert into #TBB(cuid,tbb_zj)'+@sqlrun
exec(@sqlrun)

delete order_48_105 where ord2_ordid = @ordid 

--门店人员
insert into order_48_105(ord2_ordid,ord2_tag,ord2_sspq,ord2_mdmc,ord2_mdlx,ord2_ygbh,ord2_xm,ord2_sfz,ord2_pxcuid,ord2_lxdh,ord2_zj)
SELECT  
@ordid ,
105,   
    r.ord_rzbm AS 所属片区, 
    r.ord_zzzb AS 在职店铺, 
    md.ord_dplx AS 店铺类型, 
    r.ord_gh AS 员工工号, 
    r.ord_xm AS 姓名,
    r.ord_sfzhm AS 身份证号码, 
em.cu_id AS CUID,
    r.ord_lxdh AS 联系电话,
    r.ord_zhij AS 职级
FROM dbo.order_40 AS r,dbo.mps_employee AS em, dbo.order_188 AS md ,#TBB 
WHERE  r.ord_zzzk = '在职' and  r.ord_gh = em.cu_code and r.ord_dpbh = md.ord_dpbh
and cuid = cu_id and tbb_zj<>'片区总监' and tbb_zj<>'区域经理' and tbb_zj<>'区域经理' and tbb_zj<>'督导' and tbb_zj<>'分公司总经理'

--非门店人员
insert into order_48_105(ord2_ordid,ord2_tag,ord2_sspq,ord2_mdmc,ord2_mdlx,ord2_ygbh,ord2_xm,ord2_sfz,ord2_lxdh,ord2_pxcuid,ord2_zj)
SELECT  distinct
@ordid ,
105,     
r.ord_rzbm AS 所属片区,  
'',
'',
r.ord_gh AS 员工工号, 
r.ord_xm AS 姓名,
r.ord_sfzhm AS 身份证号码, 
r.ord_lxdh AS 联系电话,
em.cu_id AS CUID,
r.ord_zhij AS 职级
FROM dbo.order_40 AS r,dbo.mps_employee AS em,#TBB
WHERE  r.ord_zzzk = '在职' and  r.ord_gh = em.cu_code
and cuid = cu_id and (tbb_zj='片区总监' or tbb_zj='区域经理' or tbb_zj='区域经理' or tbb_zj='督导' or tbb_zj='分公司总经理')

select 'ok' result 

set nocount off;
end