Related
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.
How can I split a T-SQL Command in
SELECT FROM WHERE GROUP
For example i need split this command
Text To lcSQLCommand TextMerge NoShow Flags 1 Pretext 15
SELECT a.HabitacionID, a.TipoID, b.AlquilerID, b.Desde, b.Hasta, IFNULL(b.Estado, 0) Estado,
c.Habitacion, c.Precio1 Precio
FROM habitaciones a
LEFT JOIN (SELECT HabitacionID, AlquilerID, Desde, Hasta, Estado
FROM alquiler
WHERE (Estado = 2 AND Desde <= CURDATE()) OR Estado = 1
) b ON a.HabitacionID = b.HabitacionID
LEFT JOIN habitaciones_tipo c ON a.TipoID = c.TipoID
EndText
In
lcSQLSelect = "SELECT a.HabitacionID, a.TipoID, b.AlquilerID, b.Desde, b.Hasta, IFNULL(b.Estado, 0) Estado, c.Habitacion, c.Precio1 Precio"
lcSQLFrom = "FROM habitaciones a LEFT JOIN (SELECT HabitacionID, AlquilerID, Desde, Hasta, Estado FROM alquiler WHERE (Estado = 2 AND Desde <= CURDATE()) OR Estado = 1) b ON a.HabitacionID = b.HabitacionID LEFT JOIN habitaciones_tipo c ON a.TipoID = c.TipoID"
lcWhere = "" && No Where in this command
lcGroup = "" && No Group un this command
Best regards
Ze Roberto
Text To lcSQLCommand TextMerge NoShow Flags 1 Pretext 15
SELECT a.HabitacionID, a.TipoID, b.AlquilerID, b.Desde, b.Hasta, IFNULL(b.Estado, 0) Estado,
c.Habitacion, c.Precio1 Precio
FROM habitaciones a
LEFT JOIN (SELECT HabitacionID, AlquilerID, Desde, Hasta, Estado
FROM alquiler
WHERE (Estado = 2 AND Desde <= CURDATE()) OR Estado = 1
) b ON a.HabitacionID = b.HabitacionID
LEFT JOIN habitaciones_tipo c ON a.TipoID = c.TipoID EndText
In
lcSQLSelect = "SELECT a.HabitacionID, a.TipoID, b.AlquilerID, b.Desde, b.Hasta, IFNULL(b.Estado, 0) Estado, c.Habitacion, c.Precio1 Precio"
lcSQLFrom = "FROM habitaciones a LEFT JOIN (SELECT HabitacionID, AlquilerID, Desde, Hasta, Estado FROM alquiler WHERE (Estado = 2 AND Desde <= CURDATE()) OR Estado = 1) b ON a.HabitacionID = b.HabitacionID LEFT JOIN habitaciones_tipo c ON a.TipoID = c.TipoID"
lcWhere = "" && No Where in this command
lcGroup = "" && No Group un this command
Take a look at the STREXTRACT() function. It lets you pull strings apart by specifying beginning and ending delimiters. So, for example, to get the field list, you'd use:
lcFieldList = STREXTRACT(lcSQLCommand, "SELECT", "FROM")
It gets trickier for the rest of what you need because you'll have to check for the presence of the WHERE and GROUP BY keywords to know exactly what delimiters you have, but the whole thing shouldn't be more than about 15 or 20 lines.
Note: I'm assuming you want to do this in VFP.
I would like to create a dataservice in wso2 with a query with? How to make? the query would be this:
with servicos as (
select cast(tec_servico as text) || '-' || ser_nome as servico,
ser_metodo as metodo,
coalesce(tec_vl_maximo, 0) as maximo,
teh_tipo as origem,
case when teh_dia_semana = 4410 then 0
when teh_dia_semana = 4404 then 1
when teh_dia_semana = 4405 then 2
when teh_dia_semana = 4406 then 3
when teh_dia_semana = 4407 then 4
when teh_dia_semana = 4408 then 5
when teh_dia_semana = 4409 then 6 end as dia,
teh_hora_inicial_am as hora_inicial_am,
teh_hora_final_am as hora_final_am,
teh_hora_inicial_pm as hora_inicial_pm,
teh_hora_final_pm as hora_final_pm
from tb_gcc_ted_configuracao
join tb_gfc_servico on (tec_servico = ser_cod_serial)
join tb_gcc_ted_horario on (teh_servico = tec_servico)
join tb_gen_registro on (reg_id_registro = teh_tipo)
where reg_cod_registro = :origem
and (tec_vl_maximo is null
or tec_vl_maximo > :valorLancamento)
)
select metodo
from servicos
where dia = extract(dow from current_date)
and (current_time between hora_inicial_am and hora_final_am
or current_time between hora_inicial_pm and hora_final_pm)
order by metodo
limit 1
and gives the error below:
SQL query is not applicable to automate the response
how can i do for wso2 to recognize?
I have a string to replace with the expected form.
Input: I have the following string.
'A,B,C,D,E,F,G,H,I,J,K,L'
And I want to replace the above string into the following format:
'x.A = z.A ,
x.B = z.B ,
x.C = z.C ,
x.D = z.D ,
x.E = z.E ,
x.F = z.F ,
.........
.........
x.L = z.L'
My try:
SELECT 'x.'||REPLACE('A,B,C,D,E,F,G,H,I,J,K,L',',',' = z.')
SELECT 'x.' || col || '=z.' || col
FROM (
SELECT unnest(regexp_split_to_array('A,B,C,D,E,F,G,H,I,J,K,L', ',')) col
) t
You can use string_agg and FORMAT:
SELECT string_agg(FORMAT('x.%s = z.%s', t,t) , ',')
FROM (SELECT unnest(regexp_split_to_array('A,B,C,D,E,F,G,H,I,J,K,L', ',')) AS t
) AS sub;
You can use as delimeter E',\r\n' to get carriage return:
SELECT string_agg(FORMAT('x.%s = z.%s', t,t) , E',\r\n')
FROM (SELECT unnest(regexp_split_to_array('A,B,C,D,E,F,G,H,I,J,K,L', ',')) AS t)
AS sub
Output:
x.A = z.A,
x.B = z.B,
x.C = z.C,
x.D = z.D,
x.E = z.E,
x.F = z.F,
x.G = z.G,
x.H = z.H,
x.I = z.I,
x.J = z.J,
x.K = z.K,
x.L = z.L
I have the following code which works FANTASTIC. Except - It is a sub-query to another (final) outer query and when I attempt to encapsulate this as a sub-query it refuses to run. To make it simple, I just did a "SELECT * FROM ( MY QUERY HERE)" and that even fails to run. I can only figure I am putting the right ")" in the wrong spot, but I just don't know....
Anyway - this is the query that runs fine till it is a simple sub-query:
SELECT FK_Campaign, FK_Geography, FK_InvoiceDate, FK_SalesType, FK_CustGroup, FK_Customer_Detail, FK_Parent_Detail, FK_Department, FK_Item_Detail,
FK_ItemClass_Detail, FK_ItemGroup_Detail, FK_SalesRep, FK_SalesOrigin, FK_QualityCode, FK_QualityDetailCode, FK_ResponsibilityCode,
FK_NewItemFlag, FK_TransDate, FK_CreatedDate, FK_VMReceivedDate, FK_ReturnAction, FK_StatusCode, ABC.InvoiceId, SalesID, VMRaNumber,
RetDays, ReturnQty, LineAmountmst, Qty, ReturnDays, ReturnLineAmount, ListPrice, ABC.InventTransId, ABC.ItemId,
ZZZ.FK_InventSerialProdDate AS FK_InventSerialProdDate
FROM
(SELECT
ISNULL((SELECT campaignkey --PK_Campaign
FROM VMDWAnalytical.DBO.DIM_Campaign
WHERE CampaignID = ST.smmCampaignID), -99) FK_Campaign,
ISNULL((SELECT PK_Geography
FROM VMDWAnalytical.DBO.DIM_Geography G
WHERE G.Country = ISNULL(CIJ.DLVCountryRegionID, 'zUnknown')
AND G.State = ISNULL(CIJ.DLVState, 'zUnknown')
AND G.Zip = ISNULL(CIJ.DLVZipCode, 'zUnknown')), -99) FK_Geography,
ISNULL((SELECT T.TIMEKEY
FROM VMDWAnalytical.DBO.DIM_Time T
WHERE T.FullDate = CIJ.InvoiceDate), 1) FK_InvoiceDate,
ISNULL((SELECT PK_SalesType
FROM VMDWAnalytical.DBO.DIM_SalesType
WHERE SalesType = SL.SalesType), -99) FK_SalesType,
ISNULL((SELECT PK_CustGroup
FROM VMDWAnalytical.DBO.DIM_CustGroup
WHERE CustGroup = CT.CustGroup), -99) FK_CustGroup,
ISNULL((SELECT PK_Customer_Detail
FROM VMDWAnalytical.DBO.DIM_Customer_Detail
WHERE AccountNum = CIJ.OrderAccount), -99) FK_Customer_Detail,
ISNULL((SELECT PK_Parent_Detail
FROM VMDWAnalytical.DBO.DIM_Parent_Detail
WHERE AccountNum = CIJ.OrderAccount), -99) FK_Parent_Detail,
ISNULL((SELECT PK_Department
FROM VMDWAnalytical.DBO.DIM_Department D
WHERE D.NUM = CIT.Dimension), -99) FK_Department,
ISNULL((SELECT PK_Item_Detail
FROM VMDWAnalytical.dbo.DIM_Item_Detail
WHERE Item = IT.ItemID
AND (ConfigID = ID.ConfigID
OR ConfigID = 'NONE')), -99) FK_Item_Detail,
ISNULL((SELECT PK_ItemClass_Detail
FROM VMDWAnalytical.dbo.DIM_ItemClass_Detail
WHERE ItemID = IT.ItemID), -99) FK_ItemClass_Detail,
ISNULL((SELECT PK_ItemGroup_Detail
FROM VMDWAnalytical.dbo.DIM_ItemGroup_Detail
WHERE ItemID = IT.ItemID), -99) FK_ItemGroup_Detail,
ISNULL((SELECT PK_SalesRep
FROM VMDWAnalytical.DBO.DIM_SalesRep
WHERE SalesRep = ST.SalesResponsible), -99) FK_SalesRep,
ISNULL((SELECT PK_SalesOrigin
FROM VMDWAnalytical.DBO.DIM_SalesOrigin
WHERE OriginID = ST.SalesOriginID), -99) FK_SalesOrigin,
CASE
WHEN CIT.Qty < 0 AND RR.TransDate IS NULL THEN
-97
WHEN CIT.QTY >=0 AND RR.TransDate IS NULL THEN
-98
ELSE
ISNULL((SELECT PK_QualityCode
FROM VMDWAnalytical.dbo.DIM_QualityCode
WHERE QualityCode = RR.VMQualityCode), -99)
END FK_QualityCode,
CASE
WHEN CIT.Qty < 0 AND RR.TransDate IS NULL THEN
-97
WHEN CIT.QTY >=0 AND RR.TransDate IS NULL THEN
-98
ELSE
ISNULL((SELECT PK_QualityDetailCode
FROM VMDWAnalytical.dbo.DIM_QualityDetailCode
WHERE QualityDetailCode = SL.VMQualityDetailCode
AND QualityCode = RR.VMQualityCode), -99)
END FK_QualityDetailCode,
CASE
WHEN CIT.Qty < 0 AND RR.TransDate IS NULL THEN
-97
WHEN CIT.QTY >=0 AND RR.TransDate IS NULL THEN
-98
ELSE
ISNULL((SELECT PK_ResponsibilityCode
FROM VMDWAnalytical.dbo.DIM_ResponsibilityCode
WHERE ResponsibilityCode = RR.VMResponsibilityCode), -99)
END FK_ResponsibilityCode,
CASE
WHEN ST.CREATEDDATE <= DATEADD(YEAR, 2, (SELECT KPISTARTDATE FROM RDS_KPIInventTableRel WHERE ITEMID = IT.ITEMID)) THEN
(SELECT PK_NEWITEMFLAG FROM VMDWAnalytical.DBO.DIM_NewItemFlag WHERE NewItemFlag = 'NEW')
ELSE
(SELECT PK_NEWITEMFLAG FROM VMDWAnalytical.DBO.DIM_NewItemFlag WHERE NewItemFlag = 'EXISTING')
END FK_NewItemFlag,
ISNULL((SELECT T.TIMEKEY
FROM VMDWAnalytical.DBO.DIM_Time T
WHERE T.FullDate = RR.TransDate), 1) FK_TransDate,
ISNULL((SELECT T.TIMEKEY
FROM VMDWAnalytical.DBO.DIM_Time T
WHERE T.FullDate = RR.CreatedDate), 1) FK_CreatedDate,
ISNULL((SELECT T.TIMEKEY
FROM VMDWAnalytical.DBO.DIM_Time T
WHERE T.FullDate = RR.VMReceivedDate), 1) FK_VMReceivedDate,
CASE
WHEN CIT.Qty < 0 AND RR.TransDate IS NULL THEN
-97
WHEN CIT.QTY >=0 AND RR.TransDate IS NULL THEN
-98
ELSE
ISNULL((SELECT PK_ReturnAction
FROM VMDWAnalytical.dbo.DIM_ReturnAction
WHERE ReturnActionID = RR.ReturnActionID), -99)
END FK_ReturnAction,
CASE
WHEN CIT.Qty < 0 AND RR.TransDate IS NULL THEN
-97
WHEN CIT.QTY >=0 AND RR.TransDate IS NULL THEN
-98
ELSE
ISNULL((SELECT PK_StatusCode
FROM VMDWAnalytical.dbo.DIM_StatusCode
WHERE StatusCode = RR.VMStatusCode), -99)
END FK_StatusCode,
ISNULL(CIT.InvoiceID, 'zUnknown') InvoiceID,
ISNULL(CIT.InventTransId, 'zUnknown') InventTransId,
ISNULL(CIT.ItemId, 'zUnknown') ItemId,
ISNULL(ST.SalesID, 'zUnknown') SalesID,
ISNULL(RR.VMRaNumber, 'zUnknown') VMRaNumber,
CASE
--A, Take out the Service item, flag with -98
WHEN IT.ITEMGROUPID = 'SERVICE' THEN
-98
--B, There is an original SO and the difference between the dates is non-negative
WHEN (SELECT ST1.CREATEDDATE FROM RDS_SALESTABLE ST1 WHERE ST1.SALESID = ST.PURCHORDERFORMNUM) IS NOT NULL
AND DATEDIFF(DAY, (SELECT ST1.CREATEDDATE FROM RDS_SALESTABLE ST1 WHERE ST1.SALESID = ST.PURCHORDERFORMNUM), ST.CREATEDDATE) >= 0 THEN
DATEDIFF(DAY, (SELECT ST1.CREATEDDATE FROM RDS_SALESTABLE ST1 WHERE ST1.SALESID = ST.PURCHORDERFORMNUM), ST.CREATEDDATE)
--C, The last 10 characters of the refnum field start with SOR, and the orig SO date is not null and the difference between the dates is non-negative
WHEN RIGHT(ST.PURCHORDERFORMNUM, 10) LIKE 'SOR%' AND (SELECT ST1.CREATEDDATE FROM RDS_SALESTABLE ST1 WHERE ST1.SALESID = RIGHT(ST.PURCHORDERFORMNUM, 10)) IS NOT NULL
AND DATEDIFF(DAY, (SELECT ST1.CREATEDDATE FROM RDS_SALESTABLE ST1 WHERE ST1.SALESID = RIGHT(ST.PURCHORDERFORMNUM, 10)), ST.CREATEDDATE) >= 0 THEN
DATEDIFF(DAY, (SELECT ST1.CREATEDDATE FROM RDS_SALESTABLE ST1 WHERE ST1.SALESID = RIGHT(ST.PURCHORDERFORMNUM, 10)), ST.CREATEDDATE)
--D, There is an original SO and the difference between the dates is negative
WHEN (SELECT ST1.CREATEDDATE FROM RDS_SALESTABLE ST1 WHERE ST1.SALESID = ST.PURCHORDERFORMNUM) IS NOT NULL
AND DATEDIFF(DAY, (SELECT ST1.CREATEDDATE FROM RDS_SALESTABLE ST1 WHERE ST1.SALESID = ST.PURCHORDERFORMNUM), ST.CREATEDDATE) < 0 THEN
DATEDIFF(DAY, (SELECT SCT.CAMPAIGNDATE FROM RDS_SMMCAMPAIGNTABLE SCT WHERE SCT.CAMPAIGNID = ST.SMMCAMPAIGNID), ST.CREATEDDATE)
--E, The last 10 characters of the refnum field start with SOR, and the orig SO date is not null, and the difference between the dates is negative
WHEN RIGHT(ST.PURCHORDERFORMNUM, 10) LIKE 'SOR%' AND (SELECT ST1.CREATEDDATE FROM RDS_SALESTABLE ST1 WHERE ST1.SALESID = RIGHT(ST.PURCHORDERFORMNUM, 10)) IS NOT NULL
AND DATEDIFF(DAY, (SELECT ST1.CREATEDDATE FROM RDS_SALESTABLE ST1 WHERE ST1.SALESID = RIGHT(ST.PURCHORDERFORMNUM, 10)), ST.CREATEDDATE) < 0 THEN
DATEDIFF(DAY, (SELECT SCT.CAMPAIGNDATE FROM RDS_SMMCAMPAIGNTABLE SCT WHERE SCT.CAMPAIGNID = ST.SMMCAMPAIGNID), ST.CREATEDDATE)
--F, If the campaign date <> 1/1/1900 and the datediff is positive
WHEN (SELECT SCT.CAMPAIGNDATE FROM RDS_SMMCAMPAIGNTABLE SCT WHERE SCT.CAMPAIGNID = ST.SMMCAMPAIGNID) <> '1/1/1900'
AND DATEDIFF(DAY, (SELECT SCT.CAMPAIGNDATE FROM RDS_SMMCAMPAIGNTABLE SCT WHERE SCT.CAMPAIGNID = ST.SMMCAMPAIGNID), ST.CREATEDDATE) >= 0 THEN
DATEDIFF(DAY, (SELECT SCT.CAMPAIGNDATE FROM RDS_SMMCAMPAIGNTABLE SCT WHERE SCT.CAMPAIGNID = ST.SMMCAMPAIGNID), ST.CREATEDDATE)
--G, If the difference between the Return SO and the Return and Repair transdate is positive
WHEN DATEDIFF(DAY, ST.CREATEDDATE, RR.TRANSDATE) > 0 THEN
DATEDIFF(DAY, ST.CREATEDDATE, RR.TRANSDATE)
--H
ELSE
-97
END RETDAYS,
--RETURNS
-1 * (CASE
WHEN SL.SALESTYPE = 4 THEN
CIT.LINEAMOUNTMST
ELSE
0
END) AS ReturnLineAmount,
-1 * (CASE
WHEN SL.SALESTYPE = 4 THEN
CIT.QTY
ELSE
0
END) AS ReturnQty,
--/RETURNS
(CIT.LINEAMOUNTMST) AS LineAmountMst, --Measure
(CIT.QTY) AS Qty, --Measure
ISNULL(DATEDIFF(DAY, RR.CreatedDate, RR.TransDate), 0) ReturnDays,
ITMS.PRICE AS ListPrice --Measure
FROM RDS_CUSTINVOICETRANS CIT
LEFT JOIN RDS_CUSTINVOICEJOUR CIJ
ON CIT.INVOICEID = CIJ.INVOICEID
JOIN RDS_CUSTTABLE CT
ON CIJ.ORDERACCOUNT = CT.ACCOUNTNUM
LEFT JOIN RDS_ADDRESSCOUNTRYREGION ACR
ON CIJ.DLVCOUNTRYREGIONID = ACR.COUNTRYREGIONID
LEFT JOIN RDS_SALESTABLE ST
ON CIJ.SALESID = ST.SALESID
LEFT JOIN RDS_SALESLINE SL
ON CIT.INVENTTRANSID = SL.INVENTTRANSID
LEFT JOIN RDS_INVENTTABLE IT
ON CIT.ITEMID = IT.ITEMID
LEFT JOIN RDS_INVENTTABLEMODULE ITMS
ON IT.ITEMID = ITMS.ITEMID
AND ITMS.MODULETYPE = 2
LEFT JOIN RDS_VMRETURNANDREPAIRTABLE RR
ON SL.SALESID = RR.SALESID
AND SL.VMRANUMBER = RR.VMRANUMBER
LEFT JOIN RDS_INVENTDIM ID
ON SL.INVENTDIMID = ID.INVENTDIMID
) ABC
--WHERE SL.SALESTYPE = 4 --and (SELECT ST1.CREATEDDATE FROM RDS_SALESTABLE ST1 WHERE ST1.SALESID = ST.PURCHORDERFORMNUM) IS NULL
LEFT JOIN
(SELECT CIT.InventTransId AS InventTransId, CIT.ItemId AS ItemId, CIT.InvoiceId AS InvoiceId,
ISNULL((SELECT T.TIMEKEY
FROM VMDWANAlytical.DBO.DIM_Time T
WHERE T.FullDate = MAX(SR.ProdDate)),1) AS FK_InventSerialProdDate
FROM RDS_CustInvoiceTrans CIT
LEFT JOIN RDS_InventTrans IVT
ON CIT.InventTransId = IVT.InventTransId AND
CIT.InvoiceId = IVT.InvoiceId AND
CIT.ItemId = IVT.ItemId
LEFT JOIN RDS_INVENTDIM ID
ON IVT.InventDimId = ID.InventDimId
LEFT JOIN RDS_InventSerial SR
ON ID.InventSerialId = SR.InventSerialId AND
IVT.ItemId = SR.ItemId
GROUP BY CIT.InventTransId, CIT.ItemId, CIT.InvoiceId) ZZZ
ON ABC.InventTransId = ZZZ.InventTransId AND
ABC.ItemId = ZZZ.ItemId AND
ABC.InvoiceId = ZZZ.InvoiceId
I think you need to add an alias to the subquery so you'd have
SELECT * FROM ( MY QUERY HERE) as MyQuery