
insert into JCL_ORG_COMP(comp_no,comp_name_short,comp_name,parent_company,forbidden_tag,
show_order,uuid,creator,delete_type,create_time)
select isnull(subcompanycode,''),subcompanyname,subcompanydesc,isnull(supsubcomid,0),
       isnull(canceled,0) ,isnull(showorder,0),uuid,1,0,getdate()
from HrmSubCompany
go


update t1 set t1.parent_company=t3.id
from JCL_ORG_COMP as t1
inner join
(select a.uuid,b.uuid as parentuuid
from HrmSubCompany as a
inner join HrmSubCompany as b on a.supsubcomid=b.id) as t2
on t1.uuid=t2.uuid
inner join JCL_ORG_COMP as t3 on t2.parentuuid=t3.uuid
go


insert into JCL_ORG_DEPT(dept_no, dept_name, dept_name_short,parent_comp,
                         dept_principal,show_order,forbidden_tag,creator,delete_type,create_time,uuid)
select a.departmentcode,a.departmentname,a.departmentmark,a.subcompanyid1,
              cast(case charindex(',',b.bmfzr)
           when 0 then cast(b.bmfzr as varchar(2000))
           else left(cast(b.bmfzr as varchar(2000)),charindex(',',b.bmfzr)-1)
       end as int) ,a.showorder,isnull(a.canceled,0),1,0,getdate(),uuid
from HrmDepartment as a
left join HrmDepartmentDefined as b on a.id=b.deptid
go


update t1
     set t1.parent_comp=t3.id
from JCL_ORG_dept as t1
inner join
(select a.uuid deptuuid,b.uuid comuuid
from HrmDepartment as a
inner join HrmSubCompany as b on a.subcompanyid1=b.id) t2 on t1.uuid=t2.deptuuid
inner join JCL_ORG_COMP as t3 on t2.comuuid=t3.uuid
go


update t1
     set t1.parent_dept=t3.id
from JCL_ORG_dept as t1
inner join
(select a.uuid deptuuid,b.uuid parentuuid
from HrmDepartment as a
inner join HrmDepartment as b on a.supdepid=b.id) t2 on t1.uuid=t2.deptuuid
inner join JCL_ORG_dept as t3 on t2.parentuuid=t3.uuid
go


insert into jcl_org_job(job_no, job_name, parent_comp, parent_dept,
                        description, work_duty, work_authority,
                        forbidden_tag, creator, delete_type, create_time,
                        show_order)
select b.jobtitlecode,b.jobtitlename,c.comid,d.deptid,
       cast(b.jobtitleremark as varchar(2000)),cast(b.jobresponsibility as varchar(2000)),
       cast(b.jobcompetency as varchar(2000)),isnull(b.canceled,0),1,0,getdate(),0
from (select distinct subcompanyid1,departmentid,jobtitle from HrmResource) as a
inner join HrmJobTitles as b on a.jobtitle=b.id
inner join
(select a.id ecid,b.id comid from HrmSubCompany a inner join JCL_ORG_COMP b on a.uuid=b.uuid) c
    on a.subcompanyid1=c.ecid
inner join
(select a.id ecid,b.id deptid from HrmDepartment a inner join JCL_ORG_DEPT b on a.uuid=b.uuid) d
    on a.departmentid=d.ecid
go