Optimization problems when migrating a function from MS SQL to Postgres - postgresql

I moved the function to Postgres. In MS SQL, it was executed in less than a second. In Postgresql, it runs for almost 6 minutes. I've been working on this problem for 6 hours, and I haven't found a reason. As I understand it, the problem is in the syntax.
In the xt_ed_registr_grp_led function, I attach the function (xt_ef_registr_pts_all) to a table in this format:
LEFT JOIN dbo.xt_ef_registr_pts_all(_D_Date, -1, NULL) AS RP_Child
ON RP_Child.link = RG.f_registr_pts
Next, I attach the code from MS SQL and Postgres.
Postgres function
...
AS
$$
BEGIN
RETURN QUERY SELECT
RP.link,
RP.f_division,
RP.f_subdivision,
RP.f_subscr,
RP.f_sale_items,
RP.f_sale_category,
RP.d_date_begin,
RP.d_date_end,
RCap.f_work_modes AS F_Work_Modes,
RP.f_energy_levels,
NP.f_conn_points,
NP.c_address_short,
CASE
WHEN COALESCE(Provinces.c_name, '') = ''
THEN NULL
ELSE LTRIM(RTRIM((COALESCE(LT_Provinces.c_prefix || ' ', '') || COALESCE(Provinces.c_name, ''))))
END AS C_Provinces,
CASE
WHEN COALESCE(Towns.c_name, '') = ''
THEN NULL
ELSE LTRIM(RTRIM((COALESCE(LT_Towns.c_prefix || ' ', '') || COALESCE(Towns.c_name, ''))))
END AS C_Towns,
CASE
WHEN COALESCE(Municipalities.c_name, '') = ''
THEN NULL
ELSE LTRIM(RTRIM((COALESCE(LT_Municipalities.c_prefix || ' ', '') || COALESCE(Municipalities.c_name, ''))))
END AS C_Municipalities,
CASE
WHEN LTRIM(RTRIM(((COALESCE(LT_Streets.c_prefix || ' ', '') || COALESCE(Streets.c_name, '')) || COALESCE(', ' || CP.c_building_num, '') ||
COALESCE(COALESCE(' ' || sbct.c_short_name, ' ' || sbct.c_name, '/') || CP.c_building_corp, '')))) = ''
THEN NULL
ELSE LTRIM(RTRIM(((COALESCE(LT_Streets.c_prefix || ' ', '') || COALESCE(Streets.c_name, '')) || COALESCE(', ' || CP.c_building_num, '') ||
COALESCE(COALESCE(' ' || sbct.c_short_name, ' ' || sbct.c_name, '/') || CP.c_building_corp, ''))))
END AS C_Street_Building,
RCM.f_calc_methods,
RCM.d_date AS D_Calc_Methods_Date,
CASE
WHEN EXISTS(SELECT
0
FROM dbo.ed_registr_grp RG1
WHERE RG1.f_registr_pts_main = RP.link
)
THEN TRUE
ELSE FALSE
END AS B_Group,
CASE
WHEN EXISTS(SELECT
0
FROM dbo.ed_registr_grp RG1
WHERE RG1.f_registr_pts = RP.link
)
THEN TRUE
ELSE FALSE
END AS B_IncludeGroup,
dbo.xt_ef_registr_pts_energy_categ(RP.f_sale_items, RP.f_tariff, RP.f_energy_levels) AS F_Energy_Category,
RP.f_registr_pts_prev,
D.link AS F_Device,
EDP.f_division AS f_device_division,
D.n_rate,
D.n_rate * dbo.ui_ef_device_transf_rate(D.f_division, D.link, COALESCE(_D_Date, NOW())) AS N_Ktf,
Dig.c_digits,
EDC.c_name AS C_Device_Category_Name,
EDC.f_class,
D.f_device_types,
D.c_serial_number,
EDP.f_energy_types,
EDP.n_percent2,
EDP.b_main AS B_Device_Main,
D.d_setup_date,
D.d_replace_date,
EDP.n_percent,
RPT.f_tariff,
RPT.d_date::timestamptz(0)::text AS D_Tariff_Date,
RPT.f_norms,
RCon.n_cons AS N_Cons_Cons,
RCon.n_cons2 AS N_Cons_Cons2,
RCon.d_date AS D_Cons_Date,
RCap.n_cap AS N_Cap_Cons,
RCap.n_cap2 AS N_Cap_Cons2,
RCap.n_cap3 AS N_Cap_Cons3,
RCap.d_date AS D_Cap_Date,
RPA.n_rate AS N_Activity_Rate,
RPA.d_date AS D_Activity_Date,
RP.c_code AS n_code,
RP.c_name,
RP.f_balance_types,
RP.f_balance_type_details,
RP.f_balance_types_sec,
RP.f_balance_type_details_sec,
RP.n_order,
RP.b_non_heat_formula,
RP.b_line_formula,
RP.b_transf_formula,
RP.f_transf_types,
SDA.link AS F_Areas,
erpa.d_date AS D_Areas_Date,
RP.b_notinclude,
RP.f_form_46,
RP.f_cons_category,
RP.s_owner,
RP.s_create_date,
RP.s_modif_date,
RP.s_creator,
NP.link AS F_Network_Pts,
NP.c_code AS C_Network_Pts_Code,
NR.c_network_path AS _Bound_F_Network_Pts,
NR.c_network_path_short AS C_Network_Path_Short,
CASE
WHEN NIP.f_parent IS NOT NULL
THEN dbo.cf_get_network_name(COALESCE(NI_P.f_networks, NI.f_networks))
END AS _Bound_F_Network,
FSI.c_name AS _Bound_F_Sale_Items,
EDT.c_name || COALESCE(' / ' || EDT.c_modification, '') AS _Bound_F_Device_Types,
(dbo.cf_get_c_codename(FT.n_code, FT.c_name) || ' / ' || CAST(COALESCE(FTH.n_tariff, '0') AS text) || 'р.') AS _Bound_F_Tariff,
FTH.n_tariff AS N_Tariff1,
FTH.n_tariff_2 AS N_Tariff2,
EEL.c_name AS _Bound_F_Energy_Levels,
ECM.c_name || COALESCE(' / ' || ECM2.c_name, '') AS _Bound_F_Calc_Methods,
COALESCE(EBT.c_short_name, EBT.c_name) AS _Bound_F_Balance_Types,
COALESCE(EET.c_short_name, EET.c_name) AS _Bound_F_Energy_Types,
ESWM.c_name AS _Bound_F_Work_Modes,
ELA.c_name AS _Bound_F_Transf_Algorithms,
ELA2.c_name AS _Bound_F_Line_Algorithms,
ELA3.c_name AS _Bound_F_Non_Heat_Algorithms,
SDA.c_name AS _Bound_F_Areas,
CP.c_code_cp AS N_Conn_Points_Code,
COALESCE(CP.c_name, NP.c_address_short) AS C_Conn_Points_Name,
COALESCE(CPS.c_name, '') || COALESCE(' ' || CT.c_name_short, '') || COALESCE(' № ' || CPS.c_premise_number, '') AS C_Conn_Points_Sub_Name,
CPS.c_premise_number AS C_Premise_Number,
COALESCE((CPS.j_custom ->> 'j_b_dryers')::bool, (CP.j_custom ->> 'j_b_dryers')::bool) AS B_Polotenchik,
COALESCE((CPS.j_custom ->> 'j_b_riser_insulation')::bool, (CP.j_custom ->> 'j_b_riser_insulation')::bool) AS B_Isolation,
COALESCE((CPS.j_custom ->> 'j_b_external_gvs')::bool, (CP.j_custom ->> 'j_b_external_gvs')::bool) AS B_OuterGVS,
CP.f_conn_types AS F_Conn_Types,
CP.f_conn_status_types AS F_Conn_Status_Types,
FSC.c_name AS _Bound_F_Sale_Category,
ETT.c_name AS _Bound_F_Transf_Types,
FN.c_name AS _Bound_F_Norms,
dbo.cf_get_network_name(COALESCE(NI_P.f_networks, NI.f_networks)) AS C_Network_Path,
RP.n_graph_form,
RP.n_line_loss,
RP.n_rp_loss,
NP.f_conn_points_sub,
RPL_Non_Heat.d_date_begin AS D_Non_Heat_Date,
RPL_Non_Heat.n_value AS N_Non_Heat_Waste,
RPL_Non_Heat.f_loss_algorithms AS F_Non_Heat_Algorithms,
RPL_Line.d_date_begin AS D_Line_Date,
RPL_Line.n_value AS N_Line_Waste,
RPL_Line.f_loss_algorithms AS F_Line_Algorithms,
RPL_Transf.d_date_begin AS D_Transf_Date,
RPL_Transf.n_value AS N_Transf_Waste,
RPL_Transf.f_loss_algorithms AS F_Transf_Algorithms,
s.n_code AS N_Code_Subscr,
p.c_name1 AS C_Name_Subscr
FROM dbo.ed_registr_pts AS RP
LEFT JOIN dbo.sd_subscr AS s
ON s.link = RP.f_subscr
LEFT JOIN dbo.cd_partners AS p
ON p.link = s.f_partners
LEFT JOIN dbo.ed_network_pts AS NP
ON NP.link = RP.f_network_pts
AND NP.b_pod = TRUE
LEFT JOIN LATERAL
( SELECT
NIPX.link,
NIPX.f_parent
FROM dbo.ed_network_struct NIPX
WHERE NIPX.f_child = NP.link
AND NIPX.b_pod = TRUE
AND NIPX.b_ismain = TRUE
AND NIPX.d_date_begin <= COALESCE(_D_Date, NOW())
ORDER BY
NIPX.d_date_begin DESC
LIMIT 1
) AS NIP
ON TRUE
LEFT JOIN LATERAL
(
SELECT
NIPX.link,
NIPX.f_parent
FROM dbo.ed_network_struct NIPX
WHERE NIPX.f_child = NP.f_network_pts
AND NIPX.b_pod = TRUE
AND NIPX.b_ismain = TRUE
AND NIPX.d_date_begin <= COALESCE(_D_Date, NOW())
ORDER BY
NIPX.d_date_begin DESC
LIMIT 1
) AS NIP_P
ON TRUE
LEFT JOIN LATERAL
(
SELECT
NRi.id,
NRi.c_network_path,
NRi.c_network_path_short
FROM dbo.ed_network_routes NRi
WHERE NRi.n_level = 0
AND NRi.link = COALESCE(NIP_P.f_parent, NIP.f_parent)
AND NOW() >= NRi.d_date0
AND NOW() < NRi.d_date1
ORDER BY
NRi.n_rate,
NRi.d_date1,
NRi.b_main DESC
LIMIT 1
) AS NR
ON TRUE
LEFT JOIN dbo.ed_network_pts NI
ON NI.link = NIP.f_parent
AND NI.b_pod = FALSE
LEFT JOIN dbo.ed_network_pts NI_P
ON NI_P.link = NIP_P.f_parent
AND NI_P.b_pod = FALSE
/* Объект и адрес */
LEFT JOIN dbo.sd_conn_points CP
ON CP.link = NP.f_conn_points
LEFT JOIN dbo.sd_conn_points_sub CPS
ON CPS.link = NP.f_conn_points_sub
LEFT JOIN dbo.cs_conn_types CT
ON CT.link = CPS.f_conn_types
LEFT JOIN dbo.ss_building_corp_type sbct
ON sbct.link = CP.f_building_corp_type
LEFT JOIN dbo.ss_locations AS Provinces
ON Provinces.link = CP.f_provinces_fias
LEFT JOIN dbo.ss_location_types AS LT_Provinces
ON LT_Provinces.link = Provinces.f_location_types
LEFT JOIN dbo.ss_locations AS Towns
ON Towns.link = CP.f_towns_fias
LEFT JOIN dbo.ss_location_types AS LT_Towns
ON LT_Towns.link = Towns.f_location_types
LEFT JOIN dbo.ss_locations AS Municipalities
ON Municipalities.link = CP.f_municipalities_fias
LEFT JOIN dbo.ss_location_types AS LT_Municipalities
ON LT_Municipalities.link = Municipalities.f_location_types
LEFT JOIN dbo.ss_locations AS Streets
ON Streets.link = CP.f_streets_fias
LEFT JOIN dbo.ss_location_types AS LT_Streets
ON LT_Streets.link = Streets.f_location_types /* Параметры ТУ */
LEFT JOIN dbo.ed_registr_pts_areas AS erpa
ON erpa.f_registr_pts = RP.link
AND erpa.d_date <= COALESCE(_D_Date, NOW())
AND erpa.d_date_end > COALESCE(_D_Date, NOW())
LEFT JOIN dbo.sd_areas AS SDA
ON SDA.link = erpa.f_areas
LEFT JOIN dbo.ed_registr_pts_loss AS RPL_Line
ON RPL_Line.f_registr_pts = RP.link
AND RPL_Line.f_loss_types = 1
AND COALESCE(_D_Date, NOW()) BETWEEN RPL_Line.d_date_begin AND RPL_Line.d_date_end
LEFT JOIN dbo.ed_registr_pts_loss AS RPL_Transf
ON RPL_Transf.f_registr_pts = RP.link
AND RPL_Transf.f_loss_types = 2
AND COALESCE(_D_Date, NOW()) BETWEEN RPL_Transf.d_date_begin AND RPL_Transf.d_date_end
LEFT JOIN dbo.ed_registr_pts_loss AS RPL_Non_Heat
ON RPL_Non_Heat.f_registr_pts = RP.link
AND RPL_Non_Heat.f_loss_types = 3
AND COALESCE(_D_Date, NOW()) BETWEEN RPL_Non_Heat.d_date_begin AND RPL_Non_Heat.d_date_end
LEFT JOIN LATERAL
(
SELECT
RPA1.n_rate,
RPA1.d_date,
RPA1.f_registr_pts
FROM dbo.ed_registr_pts_activity AS RPA1
WHERE RPA1.f_registr_pts = RP.link
AND RPA1.d_date <= COALESCE(_D_Date, NOW())
ORDER BY
d_date DESC
LIMIT 1
) AS RPA
ON TRUE
LEFT JOIN dbo.ed_registr_pts_tariff AS RPT
ON RPT.f_registr_pts = RP.link
AND COALESCE(_D_Date, NOW()) BETWEEN RPT.d_date AND RPT.d_date_end
LEFT JOIN dbo.fs_tariff AS FT
ON FT.link = RPT.f_tariff
LEFT JOIN LATERAL
(
SELECT
FTH.n_tariff,
FTH.n_tariff_2
FROM dbo.fs_tariff_history FTH
WHERE FTH.f_tariff = FT.link
AND FTH.b_default = TRUE
AND COALESCE(_D_Date, NOW()) BETWEEN FTH.d_date_begin AND FTH.d_date_end
ORDER BY
FTH.link
LIMIT 1
) AS FTH
ON TRUE
LEFT JOIN dbo.ed_registr_pts_cap AS RCap
ON RCap.f_registr_pts = RP.link
AND RCap.b_contract = FALSE
AND COALESCE(_D_Date, NOW()) BETWEEN RCap.d_date AND RCap.d_date_end
LEFT JOIN LATERAL
(
SELECT
RCon_.n_cons,
RCon_.n_cons2,
RCon_.d_date
FROM dbo.ed_registr_pts_cons AS RCon_
WHERE RP.link = RCon_.f_registr_pts
AND RCon_.b_contract = FALSE
AND COALESCE(_D_Date, NOW()) BETWEEN RCon_.d_date AND RCon_.d_date_end
ORDER BY
RCon_.d_date
LIMIT 1
) AS RCon
ON TRUE
LEFT JOIN dbo.ed_registr_pts_calc_methods AS RCM
ON RCM.f_registr_pts = RP.link
AND COALESCE(_D_Date, NOW()) BETWEEN RCM.d_date AND RCM.d_date_end
LEFT JOIN dbo.es_calc_methods AS ECM
ON ECM.link = RCM.f_calc_methods
LEFT JOIN dbo.es_calc_methods AS ECM2
ON ECM2.link = RCM.f_calc_methods_default
LEFT JOIN LATERAL
(
SELECT
EDP1.link,
EDP1.f_devices,
EDP1.f_energy_types,
EDP1.n_percent,
EDP1.n_percent2,
EDP1.b_main,
EDP1.f_division
FROM dbo.ed_devices_pts EDP1
INNER JOIN dbo.ed_devices D1
ON D1.link = EDP1.f_devices
AND D1.d_setup_date <= COALESCE(_D_Date, NOW())
WHERE EDP1.f_registr_pts = RP.link
ORDER BY
D1.d_setup_date DESC
LIMIT 1
) AS EDP
ON TRUE
LEFT JOIN dbo.ed_devices D
ON D.link = EDP.f_devices
LEFT JOIN dbo.es_device_types EDT
ON EDT.link = D.f_device_types
LEFT JOIN dbo.es_device_categories EDC
ON EDC.link = EDT.f_device_categories
LEFT JOIN LATERAL dbo.ef_device_digits_list(D.link) AS Dig
ON TRUE
LEFT JOIN dbo.fs_sale_items AS FSI
ON FSI.link = RP.f_sale_items
LEFT JOIN dbo.fs_sale_categories AS FSC
ON FSC.link = RP.f_sale_category
LEFT JOIN dbo.es_energy_levels AS EEL
ON EEL.link = RP.f_energy_levels
LEFT JOIN dbo.es_balance_types AS EBT
ON EBT.link = RP.f_balance_types
LEFT JOIN dbo.es_loss_algorithms AS ELA
ON ELA.link = RP.f_transf_algorithms
LEFT JOIN dbo.es_loss_algorithms AS ELA2
ON ELA2.link = RP.f_line_algorithms
LEFT JOIN dbo.es_loss_algorithms AS ELA3
ON ELA3.link = RP.f_non_heat_algorithms
LEFT JOIN dbo.fs_norms FN
ON FN.link = RPT.f_norms
LEFT JOIN dbo.es_transf_types AS ETT
ON ETT.link = RP.f_transf_types
LEFT JOIN dbo.es_work_modes AS ESWM
ON ESWM.link = RCap.f_work_modes
LEFT JOIN dbo.es_energy_types AS EET
ON EET.link = EDP.f_energy_types
WHERE RP.d_date_begin <= COALESCE(_D_Date, NOW())
AND RP.f_division = COALESCE(_F_Division, RP.f_division)
AND (
_F_Areas = -1
OR _F_Areas = erpa.f_areas
OR (
_F_Areas IS NULL
AND erpa.f_areas IS NULL
)
OR (
_F_Areas IS NULL
AND erpa.f_areas = 0
)
);
END;
$$;
Initially, I thought the problem was in the tables used, because the structure has changed, but I checked the function with the replacement with the necessary ones, nothing has changed. So I think the problem is not in the tables.

Related

Postgres OUTER JOINS TABLE ALREADY JOINED

i'm facing issues migrating queries from Oracle to Postgres 15. How can i join a table that is already joined? The Oracle looks like this:
select ltd1.short_description || '_' || to_char( CASE WHEN lsd.origine_type_id = 2 THEN
lsd.data_normalizzazione_mail
ELSE lsd.data_normalizzazione_web
END, 'YYYYMMDD_HH24MISS' ) Transazione,
lkc.kit_name || '_' || lkc.doc_name Documento_Idkit_iddoc,
lp.codice_pratica Pratica,
to_char( CASE WHEN lsd.origine_type_id = 2 THEN lsd.data_normalizzazione_mail ELSE lsd.data_normalizzazione_web END, 'DD/MM/YYYY HH24:MI:SS' ) Data_Inizio,
ltd1.long_description Tipologia_Documento,
CASE WHEN lsd.origine_type_id = 2 THEN 'Digitale' ELSE 'Cartaceo' END Tipologia_Arrivo,
lsc.sla_period || ' ore' Sla,
to_char( lsd.data_fine_trans, 'DD/MM/YYYY HH24:MI:SS' ) Data_Fine_Lavorazione,
ltd2.short_description Fase_Lavorazione,
case when ((lsd.sla_period * 60) - lsd.min_elapsed) <= 0 then 999999999 else ((lsd.sla_period * 60) - lsd.min_elapsed) end Tempo_Residuo,
to_char( lsd.data_prevista_fine_sla, 'DD/MM/YYYY HH24:MI:SS' ) Data_Previsione_Chiusura_SLA,
lsd.alert_sla Alert,
lsd.stato_sla_type_id Stato_Lav,
lsd.in_sla,
lsd.out_of_sla OutSla
from gdf_suez.ld_sla_detail lsd,
gdf_suez.ls_type_description ltd1,
gdf_suez.ld_documenti ld,
gdf_suez.ls_kit_config lkc,
gdf_suez.ld_pratiche lp,
gdf_suez.ls_sla_config lsc,
gdf_suez.ls_type_description ltd2,
gdf_suez.ld_mail lm
where ltd1.context = 'DOC_TYPE_ID'
and ltd1.type_id = lsd.doc_type_id
and ld.trans_id(+) = lsd.trans_id
and lm.trans_id(+) = lsd.trans_id
and lkc.kit_id(+) = ld.kit_id
and lp.pratica_id(+) = ld.pratica_id
and lsc.doc_type_id = lsd.doc_type_id
and lsc.doc_subtype_id = lsd.doc_subtype_id
and lsc.giorno_id = 1
and ltd2.context = 'DOC_STATUS_TYPE_ID'
and ltd2.type_id = lsd.stato_sla_type_id
and decode( lsd.origine_type_id, 2, lsd.data_normalizzazione_mail, lsd.data_normalizzazione_web) between to_date( '2022-02-01', 'YYYY-MM-DD' ) and to_timestamp( '2022-02-28 23:59:59', 'YYYY-MM-DD HH24:MI:SS' )
and lsd.stato_trans_type_id >= 0
and lm.email_stato_type_id not in (6,16)
order by Alert desc, Stato_Lav, Tempo_Residuo
When i try to rewrite it on postgres, the table gdf_suez.ld_documenti ld needs to be joined to 3 tables, and one of those 3 needs to be joined to another table. How do i fix this?
Tried to rewrite the query but the error "table name "ld" specified more than once" is thrown
from gdf_suez.ld_sla_detail lsd
LEFT OUTER JOIN gdf_suez.ld_documenti ld ON lsd.trans_id = ld.trans_id
LEFT OUTER JOIN gdf_suez.ld_mail lm ON lsd.trans_id = lm.trans_id,
gdf_suez.ls_type_description ltd1,
gdf_suez.ld_documenti ld
LEFT OUTER JOIN gdf_suez.ls_kit_config lkc ON ld.kit_id = lkc.kit_id
LEFT OUTER JOIN gdf_suez.ld_pratiche lp ON ld.pratica_id = lp.pratica_id,
gdf_suez.ls_sla_config lsc,
gdf_suez.ls_type_description ltd2
It is always easy to translate from Oracle's outdated outer join syntax to the more powerful syntax of the SQL standard: put everything that has a (+) on the right side of a LEFT JOIN. So your FROM clause would become
FROM gdf_suez.ls_type_description AS ltd1
JOIN gdf_suez.ld_sla_detail AS lsd
ON ltd1.type_id = lsd.doc_type_id
JOIN gdf_suez.ls_sla_config AS lsc
ON lsc.doc_type_id = lsd.doc_type_id
AND lsc.doc_subtype_id = lsd.doc_subtype_id
JOIN gdf_suez.ls_type_description AS ltd2
ON ltd2.type_id = lsd.stato_sla_type_id
LEFT JOIN gdf_suez.ld_mail AS lm
ON lm.trans_id = lsd.trans_id
LEFT JOIN gdf_suez.ld_documenti AS ld
ON ld.trans_id = lsd.trans_id
LEFT JOIN gdf_suez.ls_kit_config AS lkc
ON lkc.kit_id = ld.kit_id
LEFT JOIN gdf_suez.ld_pratiche AS lp
ON lp.pratica_id = ld.pratica_id

Need to replace case statement in where clause

**The below query is working badly, and I'm planning to replace case stmt in where clause with temp table. Pls suggest to me some option to rewrite this query
Is there a way to simplify this into multiple SQLs
Also explain me how this case stmt works in where clause**
select DISTINCT
ph.order_type_cd,
c.order_num,
ph.created_date,
os.order_status_desc,
ph.facility_name,
PH.vendor_order_num,
l.lic_nm,
(u.last_nm + ', ' + u.first_nm )as requestor_nm,
bl.billing_location_desc,
ph.ship_to_name,
dm.dispatch_method_name_desc as courier,
PH.po_last_updated_dt as last_updated_date,
(u1.last_nm + ', ' + u1.first_nm )as last_updated_by,
ph.right_grp_id,
c.line_id,
a.material_product_id,
a.parent_material_product_id
from avt_po_detail c
inner join avt_po_hdr ph on ph.order_num = c.order_num
left outer join avt_material_product AS a on a.material_product_id=c.material_product_id
INNER JOIN #entity_ids po on po.entity_id = c.order_num --or #select_pos = 0 )
LEFT OUTER JOIN dbo.ert_product AS pc ON pc.product_id = a.product_id
left outer join ert_product_type as pt on pt.product_type_cd = pc.product_type_cd
LEFT OUTER JOIN dbo.ert_product_xref as xref on xref.product_id = a.parent_product_id AND xref.version_id = 1
left outer join avt_order_status AS OS ON OS.order_status_cd = PH.order_status_cd
left outer join avt_licensee l on l.lic_id = ph.lic_id
left outer join avt_po_from pf on pf.material_product_id = a.material_product_id and pf.line_id = c.line_id
left outer join avt_po_audio_detail pad on pad.line_id = c.line_id
left outer join avt_materials_trans_material MTM on mtm.sequence_no = c.video_seq_no
left outer join avt_user u on u.userid = ph.requestor_id
left outer join avt_user u1 on u1.userid = ph.po_last_updated_by
left outer join avt_billing_location bl on bl.billing_location_cd = PH.billing_location_cd
left outer join avt_dispatch_method_name dm on dm.dispatch_method_name_id = PH.dispatch_method_name_id
left outer join avt_right_group arg on arg.right_grp_id = ph.right_grp_id
left outer join #prod product on product.product_id=a.product_id and (product.version_id=c.dist_version_id OR product.version_id = 1)
where (pf.from_desc in ( select from_desc from #from_desc ) or #select_form = 0)
and (case WHEN c.dist_version_id IS NULL THEN c.UCS_prod_no
ELSE
CASE
WHEN isnull(pt.version_control_ind, 'N') = 'Y' THEN xref.rss_prod_no
WHEN
isnull(pt.version_control_ind, 'N') = 'N' AND
xref.rss_prod_no IS NULL AND
xref.rss_film_id IS NULL THEN xref.rss_titleid
WHEN
isnull(pt.version_control_ind, 'N') = 'N' AND
xref.rss_prod_no IS NOT NULL AND
xref.rss_film_id IS NULL THEN substring(pc.glacct, 24, 5) -- ASR 3290687
WHEN isnull(pt.version_control_ind, 'N') = 'N' AND xref.rss_film_id IS NOT NULL THEN isnull(substring(pc.glacct, 24, 5), -- ASR 3290687
(
SELECT substring(dbo.ert_product.glacct, 24, 5) -- ASR 3290687
FROM dbo.ert_product
WHERE dbo.ert_product.product_id = a.parent_product_id
))
END
END in (select prod_no from #prod_no) or #prod_no = 0)

Why am I getting Error Code: -122 SQL State: 42803?

Using ODBC connection to a DB2 instance with the select statement below it returns the following error:
Error Code: -122 SQL State: 42803
Can someone help me identify which part of the code below is raising the error
SELECT
SAB089.ZCREPRE0.CREPREDOS as ContractCode,
SAB089.ZCLIENA0.CLIENACLI as ConsentCode,
SAB089.ZCREPRE0.CREPREAGE as Branch,
(case
when SAB089.ZCREPRE0.CREPRECTA='7' then 'Open'
when SAB089.ZCREPRE0.CREPRECTA='8' then 'Closed'
end) as PhaseOfContract,
(case
when SAB089.ZCREPRE0.CREPRECTA='6' then 'GrantedButNotActivated'
when SAB089.ZCREPRE0.CREPRECTA='7' then 'GrantedAndActivated'
when SAB089.ZCREPRE0.CREPRECTA='8' then 'SettledOnTime'
end) as ContractStatus,
'Installment' as TypeOfContract,
(case
when SAB089.ZCREPRE0.CREPRENAT = '757' then 'Vehicule'
when SAB089.ZCREPRE0.CREPRENAT = '756' then 'Equipement'
when SAB089.ZCREPRE0.CREPRENAT = '758' then 'Immobilier'
end) as PurposeOfFinancing,
SAB089.ZCREDOS0.CREDOSDEV as CurrencyOfContract,
Cast(SAB089.ZCREDOS0.CREDOSMNT as DECIMAL(19,2)) as TotalAmount,
SAB089.ZCREAVI0.CREAVIMON as InstallmentAmount,
SAB089.ZCREPLA0.CREPLANPC as NumberOfInstallments,
Cast(SAB089.ZCREPRE0.CREPRECAP as DECIMAL(19,2)) as OutstandingAmount,
Cast(SAB089.ZIMPECH0.IMPECHMON as DECIMAL(19,2)) as PastDueAmount,
SAB089.ZIMPECH0.IMPECHDTI as PastDueDays,
SAB089.ZIMPDOS0.IMPDOSECH as NumberOfDueInstallments,
Cast(SUM(SAB089.ZCREAVI0.CREAVIMON + SAB089.ZCREAVI0.CREAVIMIN + SAB089.ZCREAVI0.CREAVITVA + SAB089.ZCREAVI0.CREAVIAM1)as DECIMAL(19,2)) as TotalMonthlyPayment,
(case
when SAB089.ZCREPLA0.CREPLAPCA = 'U' then 'FinalDay'
when SAB089.ZCREPLA0.CREPLAPCA = 'M' then 'Days30'
when SAB089.ZCREPLA0.CREPLAPCA = 'T' then 'Days90'
when SAB089.ZCREPLA0.CREPLAPCA = 'S' then 'Days120'
when SAB089.ZCREPLA0.CREPLAPCA = 'A' then 'Days360'
end)
as PaymentPeriodicity,
{fn substring(SAB089.ZCREMAD0.CREMADDMD,5,2)} || '-' || {fn substring(SAB089.ZCREMAD0.CREMADDMD,3,2)} || '-' || {fn substring(SAB089.ZCREMAD0.CREMADDMD,1,2)} as StartDate,
{fn substring(SAB089.ZCREAVI0.CREAVIECH,5,2)} || '-' || {fn substring(SAB089.ZCREAVI0.CREAVIECH,3,2)} || '-' || {fn substring(SAB089.ZCREAVI0.CREAVIECH,1,2)} as RealEndDate
FROM
SAB089.ZCREAVI0, SAB089.ZIMPDOS0, SAB089.ZIMPECH0, SAB089.ZCREMAD0
INNER JOIN SAB089.ZCREPRE0 ON (SAB089.ZCREPRE0.CREPREETA=SAB089.ZCREMAD0.CREMADETA and SAB089.ZCREPRE0.CREPREAGE=SAB089.ZCREMAD0.CREMADAGE and SAB089.ZCREPRE0.CREPRESCE=SAB089.ZCREMAD0.CREMADSER and SAB089.ZCREPRE0.CREPRESSE=SAB089.ZCREMAD0.CREMADSSE and SAB089.ZCREPRE0.CREPREDOS=SAB089.ZCREMAD0.CREMADDOS and SAB089.ZCREPRE0.CREPREPRE=SAB089.ZCREMAD0.CREMADPRE)
INNER JOIN SAB089.ZCREPLA0 ON (SAB089.ZCREPLA0.CREPLAETA=SAB089.ZCREPRE0.CREPREETA and SAB089.ZCREPLA0.CREPLAAGE=SAB089.ZCREPRE0.CREPREAGE and SAB089.ZCREPLA0.CREPLASER=SAB089.ZCREPRE0.CREPRESCE and SAB089.ZCREPLA0.CREPLASSE=SAB089.ZCREPRE0.CREPRESSE and SAB089.ZCREPLA0.CREPLADOS=SAB089.ZCREPRE0.CREPREDOS and SAB089.ZCREPLA0.CREPLAPRE=SAB089.ZCREPRE0.CREPREPRE)
INNER JOIN SAB089.ZCREDOS0 ON (SAB089.ZCREDOS0.CREDOSETA=SAB089.ZCREPRE0.CREPREETA and SAB089.ZCREDOS0.CREDOSAGE=SAB089.ZCREPRE0.CREPREAGE and SAB089.ZCREDOS0.CREDOSSER=SAB089.ZCREPRE0.CREPRESCE and SAB089.ZCREDOS0.CREDOSSSE=SAB089.ZCREPRE0.CREPRESSE and SAB089.ZCREDOS0.CREDOSDOS=SAB089.ZCREPRE0.CREPREDOS)
INNER JOIN SAB089.ZCREEMP0 ON (SAB089.ZCREDOS0.CREDOSETA=SAB089.ZCREEMP0.CREEMPETA and SAB089.ZCREDOS0.CREDOSAGE=SAB089.ZCREEMP0.CREEMPAGE and SAB089.ZCREDOS0.CREDOSSER=SAB089.ZCREEMP0.CREEMPSER and SAB089.ZCREDOS0.CREDOSSSE=SAB089.ZCREEMP0.CREEMPSSE and SAB089.ZCREDOS0.CREDOSDOS=SAB089.ZCREEMP0.CREEMPDOS)
INNER JOIN SAB089.ZCLIENA0 ON (SAB089.ZCLIENA0.CLIENACLI=SAB089.ZCREEMP0.CREEMPNCL)
LEFT OUTER JOIN SAB089.X89ADRESSE ON (SAB089.X89ADRESSE.ADRESCLI=SAB089.ZCLIENA0.CLIENACLI)
INNER JOIN SAB089.ZCLIENB0 ON (SAB089.ZCLIENA0.CLIENAETB=SAB089.ZCLIENB0.CLIENBETB and SAB089.ZCLIENA0.CLIENACLI=SAB089.ZCLIENB0.CLIENBCLI)
INNER JOIN SAB089.ZCLIENC0 ON (SAB089.ZCLIENA0.CLIENAETB=SAB089.ZCLIENC0.CLIENCETB and SAB089.ZCLIENA0.CLIENACLI=SAB089.ZCLIENC0.CLIENCCLI)
LEFT OUTER JOIN SAB089.ZCLILIB0 ON (SAB089.ZCLILIB0.CLILIBCLI=SAB089.ZCLIENA0.CLIENACLI)
WHERE
(
{fn substring(SAB089.ZCLILIB0.CLILIBVAL,13,1)} = 'O'
AND SAB089.ZCREMAD0.CREMADDMD >= '1120101'
AND SAB089.ZCREPRE0.CREPRECTA IN (6, 7, 8)
AND SAB089.ZCLIENA0.CLIENADOU = 'N'
)

i am geting error: PLS-00402: alias required in SELECT list of cursor to avoid duplicate column names

I have created this procedure with select data prom different tables
and populate it into one table. i am getting error:"PLS-00402: alias
required in SELECT list of cursor to avoid duplicate column names"
while compling the code
create or replace procedure hrps.Employeeall
is
cursor EMA_FILL_EMPL_ALL
IS
SELECT DISTINCT base.eme_perno " EMPL BASE PNO",
CAR.CAR_COMP_CD "COMP CODE",
PER.EPR_SALUTATION,
PER.EPR_FST_NAME,
PER.EPR_MID_NAME,
PER.EPR_LST_NAME,
TRIM(per.EPR_SALUTATION) || ' '||TRIM(per.EPR_FST_NAME) || ' ' || TRIM(per.EPR_MID_NAME) || ' ' || TRIM(per.EPR_LST_NAME) "Name",
BASE.EME_DOB,
per.epr_gender "GENDER",
NULL z1,
PER.EPR_DIFF_ABLE,
PER.EPR_DIFF_ABLE_DESC,
BASE.EME_BLOOD_GRP,
PER.EPR_AFF_ACT,
DOJ.idt_dt,
BASE.EME_CADRE,
C3.IRC_DESC cd3,
car.car_emp_class,
CAR.CAR_EMP_TYP,
BASE.EME_EMPL_STATUS,
BASE.EME_SOURCE_EMPLMNT,
CAR.CAR_PYRL,
PYRL.IPY_PYRL_DESC,
car.car_dept_cd "DEPT CODE",
org_dept.oro_desc "DEPT DESC",
car.car_sec_cd "SECTION CODE",
org_sec.oro_desc "SECTION DESC",
car.car_desgn_cd "DESGN CODE",
DES.IDS_DESGN_DESC "DESGN DESC",
CAR.CAR_PER_GRADE_CD,
CAR.CAR_SUB_GRADE_CD,
NULL z2,
NULL z3,
NULL z4,
NULL z5,
CAR.CAR_PYRL_AREA,
C1.IRC_DESC cd1,
CAR.CAR_COST_CENT_CD,
C2.IRC_DESC cd2,
NULL z6,
NULL z7,
DOS.IDT_DT,
CAR_SEP.CAR_ACTION_RSN,
C4.IRC_DESC cd4,
PDT.IDT_DT,
EDR.IDT_DT,
NULL z8,
PROM.IDT_DT,
INC.IDT_DT,
NULL z9,
NULL z10,
C5.IRC_DESC cd5,
car.car_exec_cd "EXEC HEAD",
org_exe.oro_desc "EXEC HEAD DESC",
car.car_grp_cd "GROUP CODE",
org_grp.oro_desc "GROUP DESC",
car.car_pu_cd " PU CODE",
org_pu.idp_pu_desc "PU DESC",
car.car_position_id "POSITION ID",
NULL z11,
NULL z12,
NULL z13,
NULL z14,
FATHER.FML_FSTNAME || ' ' || FATHER.FML_MIDNAME || ' ' || FATHER.FML_LSTNAME F_NAME,
SPOUCE.FML_FSTNAME || ' ' || SPOUCE.FML_MIDNAME || ' ' || SPOUCE.FML_LSTNAME S_NAME,
TRGSD.IDT_DT,
TRGED.IDT_DT,
NULL z15,
NULL z16,
NULL z17,
NULL z18,
PAN.EID_ID,
PHONE.EMC_CONTACT,
EMAIL.EMC_CONTACT,
PER.EPR_RELIGION,
PER.EPR_NATIVE_STATE,
PER.EPR_NATIONALITY,
NULL z19,
NULL z20,
NULL z21,
SYSDATE date1,
'157068' num1,
SYSDATE date2,
'157068' num2
fROM t_empl_base base
LEFT OUTER JOIN
t_ir_em_career_dtls car
ON base.eme_perno = car.car_eme_perno
AND car.car_end_dt = '31-dec-9999'
LEFT OUTER JOIN
t_ir_em_career_dtls car_SEP
ON base.eme_perno = car_SEP.car_eme_perno
AND CAR_SEP.CAR_ACTION_TYPE ='SP'
LEFT OUTER JOIN
t_ir_em_personal per
ON base.eme_perno = per.epr_eme_perno
AND per.epr_end_dt = '31-dec-9999'
LEFT OUTER JOIN
T_IR_DESGN DES
ON DES.IDS_DESGN_CODE= CAR.CAR_DESGN_CD
AND DES.IDS_LOCATION = CAR.CAR_LOC_CD
AND DES.IDS_END_DT='31-DEC-9999'
LEFT OUTER JOIN
t_ir_em_impdt pdt
ON base.eme_perno = pdt.idt_eme_perno
AND pdt.idt_type = '03'
LEFT OUTER JOIN
t_ir_em_impdt DOJ
ON base.eme_perno = DOJ.idt_eme_perno
AND DOJ.idt_type = '02'
LEFT OUTER JOIN
t_ir_em_impdt DOS
ON base.eme_perno = DOS.idt_eme_perno
AND DOS.idt_type = '04'
LEFT OUTER JOIN
t_ir_em_impdt EDR
ON base.eme_perno = EDR.idt_eme_perno
AND EDR.idt_type = '07'
LEFT OUTER JOIN
t_ir_em_impdt PROM
ON base.eme_perno = PROM.idt_eme_perno
AND PROM.idt_type = '08'
LEFT OUTER JOIN
t_ir_em_impdt INC
ON base.eme_perno = INC.idt_eme_perno
AND INC.idt_type = '09'
LEFT OUTER JOIN
t_ir_em_impdt TRGSD
ON base.eme_perno = TRGSD.idt_eme_perno
AND TRGSD.idt_type = '12'
LEFT OUTER JOIN
t_ir_em_impdt TRGED
ON base.eme_perno = TRGSD.idt_eme_perno
AND TRGSD.idt_type = '13'
LEFT OUTER JOIN
T_IR_EM_FAMILY FATHER
ON FATHER.FML_EME_PERNO= BASE.EME_PERNO
AND FATHER.FML_TYPE ='06'
LEFT OUTER JOIN
T_IR_EM_FAMILY SPOUCE
ON SPOUCE.FML_EME_PERNO= BASE.EME_PERNO
AND SPOUCE.FML_TYPE IN ('01','02')
LEFT OUTER JOIN
T_IR_PYRL PYRL
ON CAR.CAR_PYRL = PYRL.IPY_PYRL_NO
AND PYRL.IPY_END_DATE = '31-DEC-9999'
AND PYRL.IPY_LOCN_CD = CAR.CAR_LOC_CD
AND PYRL.IPY_VALID_TAG ='Y'
LEFT OUTER JOIN
t_ir_codes c2
ON TRIM (CAR.CAR_COST_CENT_CD ) = c2.irc_code
AND c2.irc_type = 'COSTC'
LEFT OUTER JOIN
t_ir_codes c1
ON TRIM (CAR.CAR_PYRL_AREA ) = c1.irc_code
AND c1.irc_type = 'PYARA'
LEFT OUTER JOIN
t_ir_codes c3
ON BASE.EME_CADRE = c3.irc_code
AND c3.irc_type = 'CADRE'
LEFT OUTER JOIN
t_ir_codes c4
ON CAR_SEP.CAR_ACTION_RSN = c4.irc_code
AND c4.irc_type = 'SEPAR'
LEFT OUTER JOIN
t_ir_codes c5
ON CAR.CAR_COMP_CD = c5.irc_code
AND c5.irc_type = 'COMP'
LEFT OUTER JOIN
T_IR_EM_ID PAN
ON PAN.EID_EME_PERNO=BASE.EME_PERNO
AND PAN.EID_ID_CODE= '02'
LEFT OUTER JOIN
T_IR_EM_CONTACT PHONE
ON PHONE.EMC_EME_PERNO =BASE.EME_PERNO
AND PHONE.EMC_CONTACT_TYPE= '04'
AND PHONE.EMC_END_DATE='31-DEC-9999'
LEFT OUTER JOIN
T_IR_EM_CONTACT EMAIL
ON EMAIL.EMC_EME_PERNO =BASE.EME_PERNO
AND EMAIL.EMC_CONTACT_TYPE= '03'
AND EMAIL.EMC_END_DATE='31-DEC-9999'
LEFT OUTER JOIN
(SELECT DISTINCT oro_object_id, oro_desc
FROM t_org_object o
WHERE o.oro_str_type = 'IRSTR'
AND o.oro_end_date = '31-DEC-9999'
AND o.oro_type = 'EX') org_exe
ON org_exe.oro_object_id = car.car_exec_cd
LEFT OUTER JOIN
(SELECT DISTINCT oro_object_id, oro_desc
FROM t_org_object o
WHERE o.oro_str_type = 'IRSTR'
AND o.oro_end_date = '31-DEC-9999'
AND o.oro_type = 'GR') org_grp
ON org_grp.oro_object_id = car.car_grp_cd
LEFT OUTER JOIN
(SELECT DISTINCT oro_object_id, oro_desc
FROM t_org_object o
WHERE o.oro_str_type = 'IRSTR'
AND o.oro_end_date = '31-DEC-9999'
AND o.oro_type = 'DP') org_dept
ON org_dept.oro_object_id = car.car_dept_cd
LEFT OUTER JOIN
(SELECT DISTINCT oro_object_id, oro_desc
FROM t_org_object o
WHERE o.oro_str_type = 'IRSTR'
AND o.oro_end_date = '31-DEC-9999'
AND o.oro_type = 'SE') org_sec
ON org_sec.oro_object_id = car.car_sec_cd
LEFT OUTER JOIN
(SELECT DISTINCT idp_pu_code, idp_pu_desc
FROM t_ir_dept_pu o
WHERE o.idp_end_dt = '31-DEC-9999') org_pu
ON org_pu.idp_pu_code = car.car_pu_cd
WHERE base.eme_empl_status = '1';
ct EMA_FILL_EMPL_ALL%ROWTYPE;
BEGIN
FOR CT IN EMA_FILL_EMPL_ALL
LOOP
INSERT INTO T_EMPL_COMN (
EMA_PERNO,
EMA_COMP_CD,
EMA_SALUTATION,
EMA_FST_NAME,
EMA_MID_NAME,
EMA_LST_NAME,
EMA_ENAME,
EMA_BIRTH_DT,
EMA_GENDER,
EMA_MARITAL_STATUS,
EMA_DIFF_ABLE_CD,
EMA_DIFF_ABLE_DESC,
EMA_BLOODGRP,
EMA_AFFIRMATIVE_ACTION_CD,
EMA_JOINING_DT,
EMA_CADRE,
EMA_CADRE_DESC,
EMA_EMP_CLASS,
EMA_EMP_TYPE,
EMA_EMPL_STATUS,
EMA_SOURCE_EMPLMNT,
EMA_PYRL,
EMA_PYRL_DESC,
EMA_DEPT_CD,
EMA_DEPT_DESC,
EMA_SECTION_CD,
EMA_SECTION_DESC,
EMA_DESGN_CD,
EMA_DESGN_DESC,
EMA_EMPL_PGRADE,
EMA_EMPL_SGRADE,
EMA_PERS_AREA,
EMA_PERS_AREA_DESC,
EMA_PERS_SUBAREA,
EMA_PERS_SUBAREA_DESC,
EMA_PYRL_AREA,
EMA_PYRL_AREA_DESC,
EMA_COST_CENTER_CD,
EMA_COST_CENTER_DESC,
EMA_PROFIT_CENTER_CD,
EMA_PROFIT_CENTER_DESC,
EMA_DISCH_DT,
EMA_DISCH_RSN_CD,
EMA_DISCH_RSN_DESC,
EMA_CS_DATE,
EMA_EXP_RETIRE_DT,
EMA_TRF_DT,
EMA_PROM_DT,
EMA_INCR_DT,
EMA_UNION_IND,
EMA_UNION_DESC,
EMA_COMP_DESC,
EMA_EXEC_HEAD,
EMA_EXEC_HEAD_DESC,
EMA_GROUP,
EMA_GROUP_DESC,
EMA_PU,
EMA_PU_DESC,
EMA_POSITION_ID,
EMA_REPORTING_TO_PNO,
EMA_DEPT_HEAD_PNO,
EMA_PERS_EXEC_PNO,
EMA_REF_PNO,
EMA_FATHERS_NAME,
EMA_SPOUSE_NAME,
EMA_TRG_ST_DT,
EMA_TRG_EN_DT,
EMA_FPF_ACNO,
EMA_EFBS_IND,
EMA_BANK_ACNO,
EMA_BANK_CD,
EMA_PANNO,
EMA_PHONE_NO,
EMA_EMAIL_ID,
EMA_RELIGION,
EMA_NATIVE_STATE,
EMA_NATIONALITY,
EMA_CHK_HOUSE,
EMA_WRK_CHK_HOUSE,
EMA_PYRL_STOP_DATE,
EMA_ENTRY_DATE,
EMA_ENTRY_USER,
EMA_LAST_UPDATE_DATE,
EMA_LAST_UPDATE_USER
)
VALUES( CT.base.eme_perno ,
CT.CAR.CAR_COMP_CD,
CT.PER.EPR_SALUTATION,
CT.PER.EPR_FST_NAME,
CT.PER.EPR_MID_NAME,
CT.PER.EPR_LST_NAME,
CT.HRPS.POP_NAME_FETCH(BASE.EME_PERNO),
CT.BASE.EME_DOB,
CT.per.epr_gender,
NULL,
CT.PER.EPR_DIFF_ABLE,
CT.PER.EPR_DIFF_ABLE_DESC,
CT.BASE.EME_BLOOD_GRP,
CT.PER.EPR_AFF_ACT,
CT.DOJ.idt_dt,
CT.BASE.EME_CADRE,
CT.C3.IRC_DESC,
CT.car.car_emp_class,
CT.CAR.CAR_EMP_TYP,
CT.BASE.EME_EMPL_STATUS,
CT.BASE.EME_SOURCE_EMPLMNT,
CT.CAR.CAR_PYRL,
CT.PYRL.IPY_PYRL_DESC,
CT.car.car_dept_cd ,
CT.org_dept.oro_desc ,
CT.car.car_sec_cd ,
CT.org_sec.oro_desc ,
CT.car.car_desgn_cd ,
CT.DES.IDS_DESGN_DESC ,
CT.CAR.CAR_PER_GRADE_CD,
CT.CAR.CAR_SUB_GRADE_CD,
NULL,
NULL,
NULL,
NULL,
CT.CAR.CAR_PYRL_AREA,
CT.C1.IRC_DESC,
CT.CAR.CAR_COST_CENT_CD,
CT.C2.IRC_DESC,
NULL,
NULL,
CT.DOS.IDT_DT,
CT.CAR_SEP.CAR_ACTION_RSN,
CT.C4.IRC_DESC,
CT.PDT.IDT_DT,
CT.EDR.IDT_DT,
NULL,
CT.PROM.IDT_DT,
CT.INC.IDT_DT,
NULL,
NULL,
CT.C5.IRC_DESC,
CT.car.car_exec_cd,
CT.org_exe.oro_desc ,
CT.car.car_grp_cd ,
CT.org_grp.oro_desc ,
CT.car.car_pu_cd ,
CT.org_pu.idp_pu_desc ,
CT.car.car_position_id,
NULL,
NULL,
NULL,
NULL,
CT.F_NAME,
CT.S_NAME,
CT.TRGSD.IDT_DT,
CT.TRGED.IDT_DT,
NULL,
NULL,
NULL,
NULL,
CT.PAN.EID_ID,
CT.PHONE.EMC_CONTACT,
CT.EMAIL.EMC_CONTACT,
CT.PER.EPR_RELIGION,
CT.PER.EPR_NATIVE_STATE,
CT.PER.EPR_NATIONALITY,
NULL,
NULL,
NULL,
SYSDATE,
'157068',
SYSDATE,
'157068');
END LOOP;
END Employeeall;
you have to make sure each column has a different alias when its in a stored proc.
ie i see duplicates:
DOJ.idt_dt,
DOS.IDT_DT,
PDT.IDT_DT,
EDR.IDT_DT,
PROM.IDT_DT,
INC.IDT_DT,
TRGSD.IDT_DT,
TRGED.IDT_DT,
just add a unique alias for each one like you've done for some of the other columns.

T-SQL Nested Subquery

I want to place this working code within a SQL Statement, OR do I need to perform a UDF.
The result set is a one line concatenation, and I want it to be place in every one of the overall result set lines.
----
MAIN QUERY
SELECT
H.CONNECTION_ID,
H.SEQUENTIAL_NO,
H.INVOICE_NUMBER,
H.INVOICE_DATE,
H.LAST_INVOICE_NUMBER,
H.LAST_INVOICE_DATE,
CAST(CASE
WHEN H.COLLECT_DEPOSIT = 1 THEN '-'
ELSE CAST(H.PAYMENT_DUE_DATE AS NVARCHAR(20))
END AS SMALLDATETIME) AS PAYMENT_DUE,
H.JOB_NUMBER,
H.CUST_JOB_NUMBER,
HDR.SALES_PERSON,
H.INSIDE_SALES_PERSON,
H.IS_LAST_INVOICE,
CASE
WHEN H.COLLECT_DEPOSIT = 1 THEN 'CASH'
ELSE H.PAYMENT_TERMS_DESCRIPTION
END AS PAYMENT_TERMS,
H.PRINTED,
H.NOTES,
CUR.ID,
CUR.CODE,
CASE CUR.CODE
WHEN 'USD' THEN '001-106624-211'
WHEN 'EUR' THEN '001-106624-101'
WHEN 'GBP' THEN '001-106624-100'
ELSE '001-106624-001'
END AS BANK_ACCT,
CUR.EXCHANGE_RATE,
H.BILL_CONTACT,
H.CUST_ACCOUNT,
H.CUST_NAME,
H.CUST_ADDR1,
H.CUST_ADDR2,
H.CUST_CITY,
H.CUST_STATE,
H.CUST_ZIP,
H.CONTACT_PHONE_NUMBER,
H.CONTACT_PHONE_NUMBER2,
H.ORDERED_BY_CONTACT,
H.SHIP_TO_NAME,
H.SHIP_TO_ADDR1,
H.SHIP_TO_ADDR2,
H.SHIP_TO_CITY,
H.SHIP_TO_STATE,
H.SHIP_TO_ZIP,
H.SITE_PHONE_NUMBER,
H.SITE_PHONE_NUMBER2,
H.OFFICE_NAME,
H.OFFICE_ADDR1,
H.OFFICE_ADDR2,
H.OFFICE_CITY,
H.OFFICE_STATE,
H.OFFICE_ZIP,
H.OFFICE_PHONE_NUMBER,
H.OFFICE_FAX_NUMBER,
H.DELIVERY_TICKET_NUMBER,
H.PO_NUMBER,
H.DUMMY_INVOICE_TEXT,
(SELECT MESSAGE FROM REPORT_MESSAGES WHERE CODE = 'INVOICE') ADVERT_MESSAGE,
(SELECT MAX(DISCOUNT_PERCENTAGE) FROM PRTINVITEM I2 WHERE I2.CONNECTION_ID = H.CONNECTION_ID AND I2.INVOICE_NUMBER = H.INVOICE_NUMBER) AS MAX_DISCOUNT,
I.ITEM,
I.DESCRIPTION,
I.QUANTITY,
I.UNIT_OF_MEASURE,
I.MINIMUM_CHARGE,
I.WEEKLY_CHARGE,
I.MONTHLY_CHARGE,
I.START_OF_BILLING_PERIOD,
I.END_OF_BILLING_PERIOD,
I.DAYS_USED,
I.WEEKS_USED,
I.DISCOUNT_PERCENTAGE,
I.TAX_CODE_FOR_ITEM,
I.INVENTORY_TYPE,
I.BILLING_LOGIC_TYPE,
I.ACTUAL_WEEKLY_CHARGE_USED,
I.DAYS_IN_ACTUAL_WEEKLY_CHARGE,
II.CHARGEABLE_DAYS,
II.CHARGEABLE_WEEKS,
II.CHARGEABLE_MONTHS,
II.FREE_DAYS_THIS_INVOICE,
CNV.TOTAL_NET_VALUE,
CNV.TOTAL_TAX_VALUE,
CNV.TOTAL_GROSS_VALUE,
CNV.TOTAL_GROSS_VALUE_NS,
CNV.NET_LINE_VALUE,
CMP.EMAIL_ADDRESS
FROM (PRTINVHDR H INNER JOIN PRTINVITEM I ON H.CONNECTION_ID = I.CONNECTION_ID AND H.INVOICE_NUMBER = I.INVOICE_NUMBER)
INNER JOIN INVOICEHDR HDR ON I.INVOICE_NUMBER = HDR.INVNO
INNER JOIN CUSTOMERS CST ON H.CUST_ACCOUNT = CST.CUSTNUM
INNER JOIN JOB JOB ON H.JOB_NUMBER = JOB.JOBNUM
INNER JOIN CURRENCY CUR ON HDR.CURRENCY_ID = CUR.ID
INNER JOIN VWCURRENCYCONVERSION CNV ON I.CONNECTION_ID = CNV.CONNECTION_ID AND I.INVC_UCOUNTER = CNV.INVC_UCOUNTER
INNER JOIN COMPANY CMP ON H.OFFICE_CODE = CMP.OFFICE
INNER JOIN INVOICEITEM II ON I.INVOICE_NUMBER = II.INVNO AND I.INVC_UCOUNTER = II.INVC_UCOUNTER
ORDER BY
H.SEQUENTIAL_NO,
I.PRINT_SEQUENCE
ASC
----
COALESCE QUERY
DECLARE
#DTICKET NVARCHAR(20),
#PUMPCATEGORYNAME NVARCHAR(3999)
SET #DTICKET = ''
SET #PUMPCATEGORYNAME = NULL
(SELECT
#DTICKET = DTICKET,
#PUMPCATEGORYNAME = COALESCE(#PUMPCATEGORYNAME + ', ', '' ) + PUMPCATEGORYNAME
FROM (SELECT
BHDR.DTICKET,
SCD.PUMPCATEGORYNAME
FROM PRTTICKHDR PHDR
INNER JOIN BIDHDR BHDR ON PHDR.DELIV_TICKET_NUMBER = BHDR.DTICKET
INNER JOIN PRTTICKITEM PITM ON PHDR.CONNECTION_ID = PITM.CONNECTION_ID AND PHDR.DELIV_TICKET_NUMBER = PITM.DELIV_TICKET_NUMBER
LEFT JOIN SUBCATEGORYDESCRIPTION SCD ON PITM.ITEM = SCD.PUMPCATEGORY
WHERE SCD.PUMPCATEGORYNAME IS NOT NULL)
SUBCATEGORYDESCRIPTION)
SELECT #DTICKET, #PUMPCATEGORYNAME
Not really sure what you are asking for but you can doing something along the lines of
Select col1 + ', ' + col2 + ', ' + col3 etc....