PL/SQL Procedure to create XML - sql

I'm very inexperienced with PL/SQL, and am tasked with creating a procedure that use need two parameters and create XML for my current select statement. I have bits and pieces of it, but am having trouble finding how to put it all together.
So I know I will need to start with the following:
PROCEDURE markviewimport_interface c_markviewimport.invoice_id NUMBER(10) = NULL c_markviewimport.filename nvarchar(30) = NULL
And I know that I will need a cursor in order to gather the data line by line.
CURSOR c_markviewimport IS SELECT DISTINCT inv.invoice_id,
vendor.segment1 vendor_num,
vendor.vendor_name,
poh.segment1 PO_NUMBER,
inv.invoice_date,
inv.invoice_num,
terms.name TERMS_NAME,
inv.invoice_amount,
inv.amount_applicable_to_discount,
inv.amount_paid,
pmt.check_date PAYMENT_DATE,
path.filename,
path.complete_filename,
path.document_id,
stamps.text,
stamps.tool_name
FROM apps.ap_invoices_all inv,
apps.ap_invoice_distributions_all dist,
apps.po_distributions_all podi,
apps.ap_invoice_payment_history_v pmt,
apps.fnd_attached_docs_form_vl fnd,
markview.mv_page_image_paths path,
apps.po_vendors vendor,
apps.po_headers_all poh,
apps.ap_terms terms,
(SELECT mp.document_id,
moi.markup_object_id,
moi.page_markups_view_id,
moi.text,
mvt.tool_name,
mp.page_id
FROM markview.mv_markup_object moi,
markview.mv_tool mvt,
markview.mv_page_markups_view mpmv,
markview.mv_page mp
WHERE moi.tool_id = mvt.tool_id
AND mp.page_id = mpmv.page_id
AND mpmv.page_markups_view_id = moi.page_markups_view_id
AND mvt.tool_id IN (SELECT mvt.tool_id
FROM markview.mv_tool
WHERE mvt.tool_name IN (
'Green Text', 'Blue Sticky Note' )
)) stamps
WHERE inv.invoice_id = To_number(fnd.pk1_value)
AND inv.invoice_id = dist.invoice_id
AND poh.po_header_id(+) = podi.po_header_id
AND podi.po_distribution_id(+) = dist.po_distribution_id
AND fnd.file_name = To_char(path.document_id)
AND inv.invoice_id = pmt.invoice_id
AND path.document_id = stamps.document_id(+)
AND path.page_id = stamps.page_id(+)
AND fnd.category_description = 'MarkView Document'
AND fnd.entity_name = 'AP_INVOICES'
AND INV.vendor_id = poh.vendor_id(+)
AND INV.terms_id = TERMS.term_id
AND inv.vendor_id = vendor.vendor_id
AND path.platform_name = 'UNIX_FS_TO_DOC_SERVER'
AND pmt.void = 'N') r_markviewimport
And lastly this is what I'm using for XML that contains every column I need.
SELECT XMLELEMENT("Item", Xmlforest(r_markviewimport.invoice_id,
r_markviewimport.vendor_num, r_markviewimport.vendor_name,
r_markviewimport.po_number,
r_markviewimport.invoice_date, r_markviewimport.invoice_num,
r_markviewimport.terms_name, r_markviewimport.invoice_amount,
r_markviewimport.amount_applicable_to_discount,
r_markviewimport.amount_paid,
r_markviewimport.payment_date,
r_markviewimport.filename, r_markviewimport.complete_filename,
r_markviewimport.document_id, r_markviewimport.text,
r_markviewimport.tool_name
)) "Item Element"
I guess I just need help, or pointed in the right direction for creating this procedure and putting it all together.

There are several ways to generate XML from tables in Oracle.
The main benefit to using the SQL functions (like XMLELEMENT and XMLFOREST) is that you don't have to iterate over a cursor line-by-line - you can do all the work in one query. Conversely, if you want to do it row-by-row with a cursor like that, using DBMS_XMLGEN would probably make more sense. You might want to do that if you have a lot of changes to make to the data before writing it to XML.
Here's a procedure to do it with XML SQL functions.
create or replace procedure markviewimport_interface (p_invoice_id number(10), p_filename nvarchar(30))
is
v_output clob;
begin
SELECT XMLELEMENT("Items", XMLAGG(XMLELEMENT("Item", Xmlforest(r_markviewimport.invoice_id,
r_markviewimport.vendor_num, r_markviewimport.vendor_name,
r_markviewimport.po_number,
r_markviewimport.invoice_date, r_markviewimport.invoice_num,
r_markviewimport.terms_name, r_markviewimport.invoice_amount,
r_markviewimport.amount_applicable_to_discount,
r_markviewimport.amount_paid,
r_markviewimport.payment_date,
r_markviewimport.filename, r_markviewimport.complete_filename,
r_markviewimport.document_id, r_markviewimport.text,
r_markviewimport.tool_name
)))).getclobval() into v_output
FROM
(SELECT DISTINCT inv.invoice_id,
vendor.segment1 vendor_num,
vendor.vendor_name,
poh.segment1 PO_NUMBER,
inv.invoice_date,
inv.invoice_num,
terms.name TERMS_NAME,
inv.invoice_amount,
inv.amount_applicable_to_discount,
inv.amount_paid,
pmt.check_date PAYMENT_DATE,
path.filename,
path.complete_filename,
path.document_id,
stamps.text,
stamps.tool_name
FROM apps.ap_invoices_all inv,
apps.ap_invoice_distributions_all dist,
apps.po_distributions_all podi,
apps.ap_invoice_payment_history_v pmt,
apps.fnd_attached_docs_form_vl fnd,
markview.mv_page_image_paths path,
apps.po_vendors vendor,
apps.po_headers_all poh,
apps.ap_terms terms,
(SELECT mp.document_id,
moi.markup_object_id,
moi.page_markups_view_id,
moi.text,
mvt.tool_name,
mp.page_id
FROM markview.mv_markup_object moi,
markview.mv_tool mvt,
markview.mv_page_markups_view mpmv,
markview.mv_page mp
WHERE moi.tool_id = mvt.tool_id
AND mp.page_id = mpmv.page_id
AND mpmv.page_markups_view_id = moi.page_markups_view_id
AND mvt.tool_id IN (SELECT mvt.tool_id
FROM markview.mv_tool
WHERE mvt.tool_name IN (
'Green Text', 'Blue Sticky Note' )
)) stamps
WHERE inv.invoice_id = To_number(fnd.pk1_value)
AND inv.invoice_id = dist.invoice_id
AND poh.po_header_id(+) = podi.po_header_id
AND podi.po_distribution_id(+) = dist.po_distribution_id
AND fnd.file_name = To_char(path.document_id)
AND inv.invoice_id = pmt.invoice_id
AND path.document_id = stamps.document_id(+)
AND path.page_id = stamps.page_id(+)
AND fnd.category_description = 'MarkView Document'
AND fnd.entity_name = 'AP_INVOICES'
AND INV.vendor_id = poh.vendor_id(+)
AND INV.terms_id = TERMS.term_id
AND inv.vendor_id = vendor.vendor_id
AND path.platform_name = 'UNIX_FS_TO_DOC_SERVER'
AND pmt.void = 'N') r_markviewimport;
DBMS_XSLPROCESSOR.clob2file(v_output, 'MY_DIRECTORY', 'output.xml');
--return v_output;
end markviewimport_interface;
/

Related

Microsoft SQL query to view

I have this complex query that i want to turn into a view.
This query comes from https://snippets.cacher.io/snippet/3e84b01b7d52b4ca7807 and i want to save it in a view or even as a table if possible.
`
/*##=============================================*/
/*## QUERY BODY */
/*##=============================================*/
/* #region QueryBody */
/* Testing variables !! Need to be commented for Production !! */
-- DECLARE #UserSIDs AS NVARCHAR(10) = 'Disabled';
-- DECLARE #CollectionID AS NVARCHAR(10) = 'SMS00001';
-- DECLARE #Locale AS INT = 2;
-- DECLARE #Categories AS NVARCHAR(250) = 'Tools';
-- DECLARE #Compliant AS INT = 0;
-- DECLARE #Targeted AS INT = 1;
-- DECLARE #Superseded AS INT = 0;
-- DECLARE #ArticleID AS NVARCHAR(10) = '';
-- DECLARE #ExcludeArticleIDs AS NVARCHAR(250) = '';
/* Variable declaration */
DECLARE #LCID AS INT = dbo.fn_LShortNameToLCID(#Locale);
DECLARE #HelperFunctionExists AS INT = 0;
/* Perform cleanup */
IF OBJECT_ID('tempdb..#MaintenanceInfo', 'U') IS NOT NULL
DROP TABLE #MaintenanceInfo;
/* Check for helper function */
IF OBJECT_ID('[dbo].[ufn_CM_GetNextMaintenanceWindow]') IS NOT NULL
SET #HelperFunctionExists = 1;
/* Initialize HealthState descriptor table */
DECLARE #HealthState TABLE (
BitMask INT
, StateName NVARCHAR(250)
)
/* Populate HealthState table */
INSERT INTO #HealthState (BitMask, StateName)
VALUES
('0', 'Healthy')
, ('1', 'Unmanaged')
, ('2', 'Inactive')
, ('4', 'Health Evaluation Failed')
, ('8', 'Pending Restart')
, ('16', 'Update Scan Failed')
, ('32', 'Update Scan Late')
, ('64', 'No Maintenance Window')
, ('128', 'Distant Maintenance Window')
, ('256', 'Expired Maintenance Window')
/* Initialize ClientState descriptor table */
DECLARE #ClientState TABLE (
BitMask INT
, StateName NVARCHAR(100)
)
/* Populate ClientState table */
INSERT INTO #ClientState (BitMask, StateName)
VALUES
('0', 'No Reboot')
, ('1', 'Configuration Manager')
, ('2', 'File Rename')
, ('4', 'Windows Update')
, ('8', 'Add or Remove Feature')
CREATE TABLE #MaintenanceInfo (
ResourceID INT
, NextServiceWindow DATETIME
)
/* Get maintenance data */
IF #HelperFunctionExists = 1
BEGIN
WITH Maintenance_CTE AS (
SELECT
CollectionMembers.ResourceID
, NextServiceWindow.Duration
, NextServiceWindow.NextServiceWindow
, RowNumber = DENSE_RANK() OVER (PARTITION BY ResourceID ORDER BY NextServiceWindow.NextServiceWindow)
, ServiceWindowType
, ServiceWindow.Enabled
FROM vSMS_ServiceWindow AS ServiceWindow
JOIN fn_rbac_FullCollectionMembership(#UserSIDs) AS CollectionMembers ON CollectionMembers.CollectionID = ServiceWindow.SiteID
JOIN fn_rbac_Collection(#UserSIDs) AS Collections ON Collections.CollectionID = CollectionMembers.CollectionID
AND Collections.CollectionType = 2 -- Device Collections
CROSS APPLY ufn_CM_GetNextMaintenanceWindow(ServiceWindow.Schedules, ServiceWindow.RecurrenceType) AS NextServiceWindow
WHERE NextServiceWindow.NextServiceWindow IS NOT NULL
AND ServiceWindowType <> 5 -- OSD Service
)
/* Populate MaintenanceInfo table and remove duplicates */
INSERT INTO #MaintenanceInfo(ResourceID, NextServiceWindow)
SELECT
ResourceID
, NextServiceWindow
FROM Maintenance_CTE
WHERE RowNumber = 1
END
/* Get update data */
;
WITH UpdateInfo_CTE
AS (
SELECT
ResourceID = Systems.ResourceID
, Missing = COUNT(*)
FROM fn_rbac_R_System(#UserSIDs) AS Systems
JOIN fn_rbac_UpdateComplianceStatus(#UserSIDs) AS ComplianceStatus ON ComplianceStatus.ResourceID = Systems.ResourceID
AND ComplianceStatus.Status = 2 -- Filter on 'Required' (0 = Unknown, 1 = NotRequired, 2 = Required, 3 = Installed)
JOIN fn_rbac_ClientCollectionMembers(#UserSIDs) AS CollectionMembers ON CollectionMembers.ResourceID = ComplianceStatus.ResourceID
JOIN fn_rbac_UpdateInfo(#LCID, #UserSIDs) AS UpdateCIs ON UpdateCIs.CI_ID = ComplianceStatus.CI_ID
AND UpdateCIs.IsSuperseded IN (#Superseded)
AND UpdateCIs.CIType_ID IN (1, 8) -- Filter on 1 Software Updates, 8 Software Update Bundle (v_CITypes)
AND UpdateCIs.ArticleID NOT IN ( -- Filter on ArticleID csv list
SELECT VALUE FROM STRING_SPLIT(#ExcludeArticleIDs, ',')
)
AND UpdateCIs.Title NOT LIKE ( -- Filter Preview updates
'[1-9][0-9][0-9][0-9]-[0-9][0-9]_Preview_of_%'
)
JOIN fn_rbac_CICategoryInfo_All(#LCID, #UserSIDs) AS CICategory ON CICategory.CI_ID = ComplianceStatus.CI_ID
AND CICategory.CategoryTypeName = 'UpdateClassification'
AND CICategory.CategoryInstanceName IN (#Categories) -- Filter on Selected Update Classification Categories
LEFT JOIN fn_rbac_CITargetedMachines(#UserSIDs) AS Targeted ON Targeted.ResourceID = ComplianceStatus.ResourceID
AND Targeted.CI_ID = ComplianceStatus.CI_ID
WHERE CollectionMembers.CollectionID = #CollectionID
AND IIF(Targeted.ResourceID IS NULL, 0, 1) IN (#Targeted) -- Filter on 'Targeted' or 'NotTargeted'
AND IIF(UpdateCIs.ArticleID = #ArticleID, 1, 0) = IIF(#ArticleID <> '', 1, 0)
GROUP BY
Systems.ResourceID
)
/* Get device info */
SELECT
Systems.ResourceID
/* Set Health states. You can find the coresponding values in the HealthState table above */
, HealthStates = (
IIF(CombinedResources.IsClient != 1, POWER(1, 1), 0)
+
IIF(
ClientSummary.ClientStateDescription = 'Inactive/Pass'
OR
ClientSummary.ClientStateDescription = 'Inactive/Fail'
OR
ClientSummary.ClientStateDescription = 'Inactive/Unknown'
, POWER(2, 1), 0)
+
IIF(
ClientSummary.ClientStateDescription = 'Active/Fail'
OR
ClientSummary.ClientStateDescription = 'Inactive/Fail'
, POWER(4, 1), 0
)
+
IIF(CombinedResources.ClientState != 0, POWER(8, 1), 0)
+
IIF(UpdateScan.LastErrorCode != 0, POWER(16, 1), 0)
+
IIF(UpdateScan.LastScanTime < (SELECT DATEADD(dd, -14, CURRENT_TIMESTAMP)), POWER(32, 1), 0)
+
IIF(ISNULL(NextServiceWindow, 0) = 0 AND #HelperFunctionExists = 1, POWER(64, 1), 0)
+
IIF(NextServiceWindow > (SELECT DATEADD(dd, 30, CURRENT_TIMESTAMP)), POWER(128, 1), 0)
+
IIF(NextServiceWindow < (CURRENT_TIMESTAMP), POWER(256, 1), 0)
)
, Missing = ISNULL(Missing, (IIF(CombinedResources.IsClient = 1, 0, NULL)))
, Device = (
IIF(
SystemNames.Resource_Names0 IS NOT NULL, UPPER(SystemNames.Resource_Names0)
, IIF(Systems.Full_Domain_Name0 IS NOT NULL, Systems.Name0 + '.' + Systems.Full_Domain_Name0, Systems.Name0)
)
)
, OperatingSystem = (
CASE
WHEN OperatingSystem.Caption0 != '' THEN
CONCAT(
REPLACE(OperatingSystem.Caption0, 'Microsoft ', ''), -- Remove 'Microsoft ' from OperatingSystem
REPLACE(OperatingSystem.CSDVersion0, 'Service Pack ', ' SP') -- Replace 'Service Pack ' with ' SP' in OperatingSystem
)
ELSE (
/* Workaround for systems not in GS_OPERATING_SYSTEM table */
CASE
WHEN CombinedResources.DeviceOS LIKE '%Workstation 6.1%' THEN 'Windows 7'
WHEN CombinedResources.DeviceOS LIKE '%Workstation 6.2%' THEN 'Windows 8'
WHEN CombinedResources.DeviceOS LIKE '%Workstation 6.3%' THEN 'Windows 8.1'
WHEN CombinedResources.DeviceOS LIKE '%Workstation 10.0%' THEN 'Windows 10'
WHEN CombinedResources.DeviceOS LIKE '%Server 6.0' THEN 'Windows Server 2008'
WHEN CombinedResources.DeviceOS LIKE '%Server 6.1' THEN 'Windows Server 2008R2'
WHEN CombinedResources.DeviceOS LIKE '%Server 6.2' THEN 'Windows Server 2012'
WHEN CombinedResources.DeviceOS LIKE '%Server 6.3' THEN 'Windows Server 2012 R2'
WHEN Systems.Operating_System_Name_And0 LIKE '%Server 10%' THEN (
CASE
WHEN CAST(REPLACE(Build01, '.', '') AS INTEGER) > 10017763 THEN 'Windows Server 2019'
ELSE 'Windows Server 2016'
END
)
ELSE Systems.Operating_System_Name_And0
END
)
END
)
, LastBootTime = (
CONVERT(NVARCHAR(16), OperatingSystem.LastBootUpTime0, 120)
)
, PendingRestart = (
CASE
WHEN CombinedResources.IsClient = 0
OR CombinedResources.ClientState = 0
THEN NULL
ELSE (
STUFF(
REPLACE(
(
SELECT '#!' + LTRIM(RTRIM(StateName)) AS [data()]
FROM #ClientState
WHERE BitMask & CombinedResources.ClientState <> 0
FOR XML PATH('')
),
' #!',', '
),
1, 2, ''
)
)
END
)
, ClientState = (
CASE CombinedResources.IsClient
WHEN 1 THEN ClientSummary.ClientStateDescription
ELSE 'Unmanaged'
END
)
, ClientVersion = CombinedResources.ClientVersion
, LastUpdateScan = (
CONVERT(NVARCHAR(16), UpdateScan.LastScanTime, 120)
)
, LastScanLocation = NULLIF(UpdateScan.LastScanPackageLocation, '')
, LastScanError = NULLIF(UpdateScan.LastErrorCode, 0)
, NextServiceWindow = IIF(CombinedResources.IsClient != 1, NULL, CONVERT(NVARCHAR(16), NextServiceWindow, 120))
FROM fn_rbac_R_System(#UserSIDs) AS Systems
JOIN fn_rbac_CombinedDeviceResources(#UserSIDs) AS CombinedResources ON CombinedResources.MachineID = Systems.ResourceID
LEFT JOIN fn_rbac_RA_System_ResourceNames(#UserSIDs) AS SystemNames ON SystemNames.ResourceID = Systems.ResourceID
LEFT JOIN fn_rbac_GS_OPERATING_SYSTEM(#UserSIDs) AS OperatingSystem ON OperatingSystem.ResourceID = Systems.ResourceID
LEFT JOIN fn_rbac_CH_ClientSummary(#UserSIDs) AS ClientSummary ON ClientSummary.ResourceID = Systems.ResourceID
LEFT JOIN fn_rbac_UpdateScanStatus(#UserSIDs) AS UpdateScan ON UpdateScan.ResourceID = Systems.ResourceID
LEFT JOIN #MaintenanceInfo AS Maintenance ON Maintenance.ResourceID = Systems.ResourceID
LEFT JOIN UpdateInfo_CTE AS UpdateInfo ON UpdateInfo.ResourceID = Systems.ResourceID
JOIN fn_rbac_FullCollectionMembership(#UserSIDs) AS CollectionMembers ON CollectionMembers.ResourceID = Systems.ResourceID
WHERE CollectionMembers.CollectionID = #CollectionID
AND (
CASE -- Compliant (0 = No, 1 = Yes, 2 = Unknown)
WHEN Missing = 0 OR (Missing IS NULL AND Systems.Client0 = 1) THEN 1 -- Yes
WHEN Missing > 0 AND Missing IS NOT NULL THEN 0 -- No
ELSE 2 -- Unknown
END
) IN (#Compliant)
/* Perform cleanup */
IF OBJECT_ID('tempdb..#MaintenanceInfo', 'U') IS NOT NULL
DROP TABLE #MaintenanceInfo;
/* #endregion */
/*##=============================================*/
/*## END QUERY BODY */
/*##=============================================*/
`
Is there an easy way to achieve this?
I have tried to look at the official Microsoft documentation but are still not able to convert the query to a view. https://learn.microsoft.com/en-us/sql/t-sql/statements/create-view-transact-sql?view=sql-server-ver16
As I am new to SQL language I am not sure where to start.
So I agree with Larnu, that this probably doesn't make a ton of sense. But there are cases where one might want to be able to run multiple batches of queries / procedural code from an object that's as consumable as a view. I've done this once in a case where I needed to maximize my options for performance tuning without losing the consumability of the object. So for the sake of when it does make sense, this is something you could do:
Wrap your code in a stored procedure.
Use OPENQUERY() to call your procedure.
Wrap the OPENQUERY() call in a view.
Limitations with this methodology is it's rather static:
You can't pass parameters to your stored procedure
If you use temp tables in your stored procedure, then you need to use the WITH RESULT SETS clause to explicitly define the shape of your result set
The procedure can only return one result set
The SQL Server Engine puts a hard-coded cardinality estimate of 10,000 against OPENQUERY(). So in cases where your procedure returns a lot more rows (typically an order of magnitude or more) than 10,000, e.g. 1 million rows, then you may experience some performance issues with joining the wrapper view to other objects.
Example:
-- Step 1: Wrap the procedural code in a stored procedure
CREATE PROCEDURE dbo.RunSomeCode
AS
BEGIN
CREATE TABLE #Results (ID INT, SomeValue VARCHAR(100));
DECLARE #SomeVariable INT = 0;
WHILE (#SomeVariable < 5)
BEGIN
SET #SomeVariable = #SomeVariable + 1;
INSERT INTO #Results (ID, SomeValue)
SELECT ID, SomeValue
FROM SomeTable
WHERE ID = #SomeVariable
END
SELECT ID, SomeValue
FROM #Results;
END
GO
-- Step 2 & 3: Wrap an OPENQUERY() call to the procedure in a view.
CREATE VIEW dbo.SomeView
AS
SELECT ID, SomeValue
FROM OPENQUERY
(
'
LocalServerName,
EXEC dbo.RunSomeCode
WITH RESULT SETS
((
ID INT,
SomeValue VARCHAR(100)
))
'
);
Voila, you can now execute the procedure by SELECTing from the view:
SELECT ID, SomeValue
FROM dbo.SomeView;

Nested in line view Add Column

I have to add a column to this report - the new column name is: uda_value_desc
The code below will give me a result if I enter a PM_ITEM number, I need to insert the code into one of the in line views.
Any help would be appreciated
WITH item_temp AS (SELECT im.item
,uv.uda_value_desc uda_value_desc -----
FROM item_master im
,TABLE(mff_report.parse_strings(:PM_item)) t
, uda_item_lov uil
, uda_values uv
WHERE t.Column_Value = uil.item
and uil.UDA_ID = 511
and uv.uda_id = uil.uda_id
and uv.uda_value = uil.uda_value
and im.item = uil.item
UNION ALL
SELECT im.item
,null
FROM item_master im
,TABLE(mff_report.parse_strings(:PM_item)) t
WHERE t.COLUMN_VALUE = im.item_parent
AND im.item_level = im.tran_level
UNION ALL
SELECT sd.item
,null
FROM skulist_detail sd
,TABLE(mff_report.parse_strings(:PM_item_list)) t
WHERE t.COLUMN_VALUE = sd.skulist
UNION ALL
SELECT ia.item
,null
FROM mffecom.item_attr ia
,TABLE(mff_report.parse_strings(:PM_product_id)) t
WHERE t.COLUMN_VALUE = ia.product_id
UNION ALL
SELECT im.item
,null
FROM item_master im
WHERE :PM_item IS NULL
AND :PM_item_list IS NULL
AND :PM_product_id IS NULL )
SELECT v_item.item_parent
,uda_value_desc
,v_item.item
,mff_report.mff_merch_sql.get_brand_name(v_item.item) brand_name
,v_item.item_desc
,v_selling.product_id
,v_product.product_web_desc
,v_product.product_template
,v_product.romance_copy
,v_selling.selling_point_1
,v_selling.selling_point_2
,v_selling.selling_point_3
,v_selling.selling_point_4
,v_selling.selling_point_5
,v_selling.selling_point_6
,v_selling.selling_point_7
,v_selling.selling_point_8
,v_selling.selling_point_9
,v_selling.selling_point_10
,v_selling.selling_point_11
,v_selling.selling_point_12
,v_selling.selling_point_13
,v_selling.selling_point_14
,v_selling.selling_point_15
,v_selling.selling_point_16
,v_item.vpn
,v_item.diff_1
,v_item.diff1_desc
,v_item.diff_2
,v_item.diff2_desc
,v_item.diff_3
,v_item.diff3_desc
,v_item.diff_4
,v_item.diff4_desc
,v_item.supplier
,v_item.sup_name
,v_product.code_desc fulfillment_method_desc
,v_product.air_ship_restrict
,v_product.do_not_freeze
,v_product.free_shipping
,v_product.refrigerate
,v_product.serial_reqd
,v_product.vaccination
,v_product.is_consumable
,v_product.zero_weight
,v_product.restrict_state
,v_product.no_of_alt_image
,v_product.product_status
,v_product.item_ecom_status
,TO_CHAR(v_product.deactivate_date, 'MM/DD/YYYY') product_deactivate_date
,TO_CHAR(v_product.product_activate_date, 'MM/DD/YYYY') product_activate_date
,TO_CHAR(v_product.item_activate_date, 'MM/DD/YYYY') item_activate_date
,TO_CHAR(v_product.item_deactivate_date, 'MM/DD/YYYY') item_deactivate_date
,v_product.prod_created_by
,TO_CHAR(v_product.prod_created_date, 'MM/DD/YYYY') prod_created_date
,v_product.prod_updated_by
,v_product.item_created_by
,TO_CHAR(v_product.item_created_date, 'MM/DD/YYYY') item_created_date
,v_product.item_updated_by
,v_item.delete_type purge
,v_item.dept
,v_item.class
,v_item.subclass
,mff_orders_sql.buyer_for_item(v_item.item) buyer
,mff_orders_sql.buyer_name_for_item(v_item.item) buyer_name
,v_item.soh
,v_item.length
,v_item.width
,v_item.height
,v_item.weight
,v_variant.variant_id1
,v_variant.value_id1
,v_variant.variant_id2
,v_variant.value_id2
,v_variant.variant_id3
,v_variant.value_id3
,v_variant.variant_id4
,v_variant.value_id4
,v_variant.variant_id5
,v_variant.value_id5
,v_variant.variant_id6
,v_variant.value_id6
FROM (SELECT ia.item
,v_sell.product_id
,MIN(DECODE(row_num,1,selling_point)) selling_point_1
,MIN(DECODE(row_num,2,selling_point)) selling_point_2
,MIN(DECODE(row_num,3,selling_point)) selling_point_3
,MIN(DECODE(row_num,4,selling_point)) selling_point_4
,MIN(DECODE(row_num,5,selling_point)) selling_point_5
,MIN(DECODE(row_num,6,selling_point)) selling_point_6
,MIN(DECODE(row_num,7,selling_point)) selling_point_7
,MIN(DECODE(row_num,8,selling_point)) selling_point_8
,MIN(DECODE(row_num,9,selling_point)) selling_point_9
,MIN(DECODE(row_num,10,selling_point)) selling_point_10
,MIN(DECODE(row_num,11,selling_point)) selling_point_11
,MIN(DECODE(row_num,12,selling_point)) selling_point_12
,MIN(DECODE(row_num,13,selling_point)) selling_point_13
,MIN(DECODE(row_num,14,selling_point)) selling_point_14
,MIN(DECODE(row_num,15,selling_point)) selling_point_15
,MIN(DECODE(row_num,16,selling_point)) selling_point_16
FROM mffecom.item_attr ia
,(SELECT sp.product_id
,row_number () OVER (PARTITION BY sp.product_id ORDER BY sp.selling_point_id) row_num
,sp.selling_point
FROM mffecom.selling_point sp
ORDER BY sp.product_id
,sp.selling_point) v_sell
WHERE ia.product_id = v_sell.product_id
GROUP BY ia.item
,v_sell.product_id) v_selling
,(SELECT NVL(im.item_parent,im.item) item_parent
,im.item
,im.item_desc
,im.dept
,im.class
,im.subclass
,isupp.supplier
,s.sup_name
,isupp.vpn
,miim.stock_on_hand soh
,iscd.length
,iscd.width
,iscd.height
,iscd.weight
,im.diff_1
,di.diff_desc diff1_desc
,im.diff_2
,di2.diff_desc diff2_desc
,im.diff_3
,di3.diff_desc diff3_desc
,im.diff_4
,di4.diff_desc diff4_desc
,dp.delete_type
FROM item_supplier isupp
,sups s
,item_supp_country_dim iscd
,item_master im
,diff_ids di
,diff_ids di2
,diff_ids di3
,diff_ids di4
,daily_purge dp
,merch_item_inv_mv miim
WHERE isupp.item = im.item
AND isupp.item = miim.item (+)
AND isupp.supplier = s.supplier
AND isupp.item = iscd.item
AND isupp.supplier = iscd.supplier
AND isupp.primary_supp_ind = 'Y'
AND iscd.dim_object = 'EA'
AND im.item_level = im.tran_level
AND im.sellable_ind = 'Y'
AND im.diff_1 = di.diff_id (+)
AND im.diff_2 = di2.diff_id (+)
AND im.diff_3 = di3.diff_id (+)
AND im.diff_4 = di4.diff_id (+)
AND im.item = dp.key_value (+)) v_item
,(SELECT ia.item
,pm.product_id
,pm.product_web_desc
,pm.template product_template
,pm.romance_copy
,ia.air_ship_restrict
,ia.do_not_freeze
,ia.free_shipping
,ia.refrigerate
,ia.serial_reqd
,ia.vaccination
,ia.is_consumable
,ia.zero_weight
,pm.no_of_alt_image
,pm.status product_status
,ia.status item_ecom_status
,pm.deactivate_date deactivate_date
,pm.activate_date product_activate_date
,ia.activate_date item_activate_date
,ia.deactivate_date item_deactivate_date
,pm.created_by prod_created_by
,pm.create_datetime prod_created_date
,pm.updated_by prod_updated_by
,ita.created_by item_created_by
,ita.create_date item_created_date
,ia.updated_by item_updated_by
,str.restrict_state
,cd.code_desc
FROM MFFECOM.product_master pm
,MFFECOM.item_attr ia
,MFFECOM.ship_to_restrict str
,rms13.mff_brand mb
,rms13.item_attributes ita
,rms13.code_detail cd
WHERE ia.product_id = pm.product_id
AND ia.item = str.item (+)
AND ia.item = ita.item (+)
AND pm.brand_id = mb.brand_id (+)
AND to_char(ia.fulfillment_method) = cd.code
AND cd.code_type = 'EIFM') v_product
,(SELECT item
,product_id
,MIN(DECODE(row_num,1,variant_id)) variant_id1
,MIN(DECODE(row_num,1,value_id)) value_id1
,MIN(DECODE(row_num,2,variant_id)) variant_id2
,MIN(DECODE(row_num,2,value_id)) value_id2
,MIN(DECODE(row_num,3,variant_id)) variant_id3
,MIN(DECODE(row_num,3,value_id)) value_id3
,MIN(DECODE(row_num,4,variant_id)) variant_id4
,MIN(DECODE(row_num,4,value_id)) value_id4
,MIN(DECODE(row_num,5,variant_id)) variant_id5
,MIN(DECODE(row_num,5,value_id)) value_id5
,MIN(DECODE(row_num,6,variant_id)) variant_id6
,MIN(DECODE(row_num,6,value_id)) value_id6
FROM (SELECT item
,product_id
,row_number () OVER (PARTITION BY item ORDER BY variant_id) row_num
,variant_id
,value_id
FROM mffecom.item_variant)
GROUP BY item
,product_id) v_variant
,item_temp it
WHERE v_item.item = v_selling.item (+)
AND v_item.item = v_product.item (+)
AND v_item.item = v_variant.item (+)
AND v_item.item = it.item
AND v_item.supplier = NVL(:PM_supplier,v_item.supplier)
AND (v_product.prod_created_by = :PM_prod_created_by OR :PM_prod_created_by IS NULL)
AND (v_product.item_created_by = :PM_item_created_by OR :PM_item_created_by IS NULL)
AND (v_product.prod_created_date BETWEEN :prod_created_date_start AND :prod_created_date_to OR :prod_created_date_start IS NULL)
AND (v_product.item_created_date BETWEEN :item_created_date_start AND :item_created_date_to OR :item_created_date_start IS NULL)
ORDER BY v_product.product_id

Expression.Error Power Query EXCEL

I have a problem with a dynamic parameter in Power Query. There's the code:
let
Parametro = Excel.CurrentWorkbook(){[Name="Parametro"]}[Content],
InicioExec_Valor = Parametro{0}[Valor],
FimExec_Valor = Parametro{1}[Valor],
Fonte = Sql.Database("DATABASE", "TABLE", [Query="select#(lf)#(lf)o.cd_controle, exe.nm_pessoa AS Executante, o.numero AS OM, #(lf)CONVERT(nvarchar(10), o.dt_abertura, 103) AS Abertura,#(lf)o.medidor Horimetro_OM,#(lf)p.nm_pessoa AS Cliente, #(lf)e.nm_equipto AS Equipamento, pat.nr_patrimonio AS Patrimonio, #(lf)CONVERT(nvarchar(10), o.dt_autoriz_execucao, 103) AS Inicio_Exec, #(lf)CONVERT(nvarchar(10), o.dt_encos_oficina, 103) AS Fim_Exec, Z.nm_apelido AS Unidade, #(lf)CASE WHEN fl_preventiva = 'C' THEN 'Corretiva' #(lf)WHEN fl_preventiva = 'P' then 'PREVENTIVA'#(lf)WHEN fl_preventiva = 'R' then 'INSPEÇÃO RESUMIDA'#(lf)WHEN fl_preventiva = 'V' then 'INSPEÇÃO PREVENTIVA'#(lf)WHEN fl_preventiva = 'E' then 'ENTREGA TÉCNICA'#(lf)else 'Indefinido' end AS 'Corret_Preven'#(lf),CONVERT(nvarchar(10), fl_remessa.dt_saida, 103) AS DataSaida#(lf),fl_rem_equ.vl_medidor Horimetro_Remessa#(lf),CONVERT(nvarchar(10), o.dt_abertura, 103) AS Abertura#(lf),o.medidor Horimetro_OM#(lf)#(lf)from orcos o#(lf)inner join controle c on (c.cd_controle = o.cd_controle)#(lf)inner join wcore_oid oid on (oid.cd_oid = c.cd_oid)#(lf)left outer join empresa AS Z ON Z.cd_empresa = o.cd_empresa #(lf)left outer join equipto e on (e.cd_equipto = o.cd_equipto)#(lf)left outer join pessoa f on (f.cd_pessoa = o.cd_pessoa_tec)#(lf)left outer join pessoa p on (p.cd_pessoa = o.cd_pessoa)#(lf)left outer join pessoa exe on (exe.cd_pessoa = o.cd_pessoa_exe)#(lf)left outer join patrimon pat on (pat.cd_patrimonio = o.cd_patrimonio)#(lf)left outer join est_almox x on x.cd_almox = pat.cd_almox#(lf)left outer join empresa emp on emp.cd_empresa = o.cd_empresa_origem #(lf)#(lf)left outer JOIN dbo.fich_loc ON (fich_loc.cd_controle= o.cd_controle_loc)#(lf)left outer JOIN dbo.fl_remessa fl_remessa ON (fl_remessa.cd_controle = dbo.fich_loc.cd_controle)#(lf)#(lf)INNER JOIN(select max(fl_remessa.cd_flremessa)cd_flremessa, A.cd_controle #(lf)#(tab)#(tab)#(tab)#(tab)#(tab) from dbo.fl_remessa#(lf)#(tab)#(tab)#(tab)#(tab)#(tab) inner join dbsislocsalvador..fich_loc on (fl_remessa.cd_controle = dbo.fich_loc.cd_controle)#(lf)#(tab)#(tab)#(tab)#(tab)#(tab)#(tab)#(tab)#(tab) inner join dbsislocsalvador..orcos a on (fich_loc.cd_controle= A.cd_controle_loc#(lf)#(tab)#(tab)#(tab)#(tab)#(tab)#(tab)#(tab)#(tab) and fl_remessa.dt_saida<=a.dt_abertura) #(lf)#(tab)#(tab)#(tab)#(tab)#(tab)#(tab)#(tab)#(tab) inner join controle c on (c.cd_controle = A.cd_controle)#(lf)#(tab)#(tab)#(tab)#(tab)#(tab)#(tab)#(tab)#(tab) #(lf)#(tab)#(tab)#(tab)#(tab)#(tab)#(tab)#(tab)#(tab) left outer join patrimon pat on (pat.cd_patrimonio = a.cd_patrimonio)#(lf)#(tab)#(tab)#(tab)#(tab)#(tab)#(tab)#(tab)#(tab) LEFT OUTER JOIN dbo.fl_rem_equ AS fl_rem_equ ON pat.cd_patrimonio = fl_rem_equ.cd_patrimonio AND fl_remessa.cd_flremessa = fl_rem_equ.cd_flremessa#(lf) #(tab)#(tab) left outer JOIN dbo.loc_flremequ_xplano AS loc_flremequ_xplano ON loc_flremequ_xplano.cd_flremequ = fl_rem_equ.cd_flremequ #(lf) #(tab)#(tab)#(tab) left outer JOIN dbo.equipto AS equipto ON fl_rem_equ.cd_equipto = equipto.cd_equipto#(lf)#(tab)#(tab)#(tab)#(tab)#(tab)#(tab)#(tab)#(tab) #(lf)#(tab)#(tab)#(tab)#(tab)#(tab)#(tab)#(tab)#(tab) where #(lf)#(tab)#(tab)#(tab)#(tab)#(tab)#(tab)#(tab)#(tab) #(lf)#(tab)#(tab)#(tab)#(tab)#(tab)#(tab)#(tab)#(tab) ((NOT EXISTS(select top 1 * from config_tag_xoid)) OR (c.cd_oid not in (select txo.cd_oid from #(lf)#(tab)#(tab)#(tab)#(tab)#(tab)#(tab)#(tab)#(tab) (select * from ( select cd_tag, nm_tag , (30) as fl_acesso from config_tag t where t.fl_ativo in ('S') ) tags #(lf)#(tab)#(tab)#(tab)#(tab)#(tab)#(tab)#(tab)#(tab) WHERE (fl_acesso = 10) ) tags inner join config_tag_xoid txo on tags.cd_tag = txo.cd_tag where 3=3 /*filter_tag_clause*/ #(lf)#(tab)#(tab)#(tab)#(tab)#(tab)#(tab)#(tab)#(tab) group by txo.cd_oid))) and ( ( (a.cd_controle_loc is not null and a.cd_fldevolucao is null) ) ) and#(lf)#(tab)#(tab)#(tab)#(tab)#(tab)#(tab)#(tab)#(tab) (a.cd_empresa IN (24,45,5,46,20,29,43,15,48,10,1,22,8,34,49,9,47,52,7)) and ( ( a.cd_local is null or a.cd_local in (0,1,2,3,5,6,7,8,9) ) ) #(lf)#(tab)#(tab)#(tab)#(tab)#(tab)#(tab)#(tab)#(tab) AND (a.cd_controle_loc IS NOT NULL) AND (a.cd_fldevolucao IS NULL) #(lf)#(tab)#(tab)#(tab)#(tab)#(tab)#(tab)#(tab)#(tab) and (a.fl_preventiva in ('C', 'P', 'R', 'V', 'E')) #(lf)#(tab)#(tab)#(tab)#(tab)#(tab)#(tab)#(tab)#(tab) and (equipto.cd_grupo in (1478, 1480, 1481, 1482, 1483, 1484, 1485, 1486, 1487, 1488, 1491, 1492, 1548, 1549))#(lf)#(tab)#(tab)#(tab)#(tab)#(tab)#(tab)#(tab)#(tab) #(lf)#(tab)#(tab)#(tab)#(tab)#(tab)#(tab)#(tab)#(tab) group by a.cd_controle) AS fl_remessa_max #(lf)#(tab)#(tab)#(tab)#(tab)#(tab)#(tab)#(tab)#(tab) ON fl_remessa.cd_flremessa = fl_remessa_max.cd_flremessa#(lf)#(tab)#(tab)#(tab)#(tab)#(tab)#(tab)#(tab)#(tab) and fl_remessa_max.cd_controle = o.cd_controle #(lf)#(tab)#(tab)#(tab)#(tab)#(tab)#(tab)#(tab)#(tab) #(lf)LEFT OUTER JOIN dbo.fl_rem_equ AS fl_rem_equ ON pat.cd_patrimonio = fl_rem_equ.cd_patrimonio AND fl_remessa.cd_flremessa = fl_rem_equ.cd_flremessa#(tab)#(tab)#(tab)#(tab)#(tab)#(tab)#(tab)#(tab) #(lf)left outer JOIN dbo.equipto AS equipto ON fl_rem_equ.cd_equipto = equipto.cd_equipto#(lf) #(tab)#(tab)#(tab)#(tab)#(tab) #(lf)WHERE ((NOT EXISTS(select top 1 * from config_tag_xoid)) OR (c.cd_oid not in (select txo.cd_oid from #(lf)(select * from ( select cd_tag, nm_tag , (30) as fl_acesso from config_tag t where t.fl_ativo in ('S') ) tags #(lf)WHERE (fl_acesso = 10) ) tags inner join config_tag_xoid txo on tags.cd_tag = txo.cd_tag where 3=3 /*filter_tag_clause*/ #(lf)group by txo.cd_oid))) and ( ( (o.cd_controle_loc is not null and o.cd_fldevolucao is null) ) ) and#(lf)(o.cd_empresa IN (24,45,5,46,20,29,43,15,48,10,1,22,8,34,49,9,47,52,7)) and ( ( o.cd_local is null or o.cd_local in (0,1,2,3,5,6,7,8,9) ) ) #(lf)AND (o.cd_controle_loc IS NOT NULL) AND (o.cd_fldevolucao IS NULL) #(lf)and (o.fl_preventiva in ('C', 'P', 'R', 'V', 'E')) #(lf)and (equipto.cd_grupo in (1478, 1480, 1481, 1482, 1483, 1484, 1485, 1486, 1487, 1488, 1491, 1492, 1548, 1549))"]),
#"Tipo Alterado" = Table.TransformColumnTypes(Fonte,{{"Abertura", type date}, {"Inicio_Exec", type date}, {"Fim_Exec", type date}, {"DataSaida", type date}}),
#"Colunas Removidas" = Table.RemoveColumns(#"Tipo Alterado",{"cd_controle", "Horimetro_OM2", "Abertura2"}),
#"Filtro Datas" = Table.SelectRows(#"Colunas Removidas", each [Fim_Exec] >= InicioExec_Valor and [Fim_Exec] <= FimExec_Valor)
in
#"Filtro Datas"
And occur that error:
Expression.Error: Não conseguimos aplicar o operador < aos tipos
Number e Date. Detalhes:
Operator=<
Left=42795
Right=01/06/2007
How can I solve that?
Note: MY PARAMETER (01/03/2017) ARE FORMATED AS TEXT.
Although I don't read Spanish, looks like it says you cannot compare number and date with < operator.
It is good practice, by the way, to first convert parameters to the proper type:
InicioExec_Valor = Date.From(Parametro{0}[Valor]),
FimExec_Valor = Date.From(Parametro{1}[Valor]),`
Try this.
If it won't work, determine step that generates error by clicking them one-by-one.
There is more I wonder about. Why do you convert Fim_Exec to nvarchar and then to date?
1. #(lf)CONVERT(nvarchar(10), o.dt_encos_oficina, 103) AS Fim_Exec
2. {"Fim_Exec", type date},
Why don't use Fim_Exec = CAST(o.dt_encos_oficina as date)? (or datetime, depending on SQL Server version) in the query?
Same applies to other columns.
Next, it is best practice not to use native queries unless absolutely required.
And, yes, this is largest and most complex query I've seen up to date. :)

Full outer join very slow

I have two tables. One is todays prices and one is yesterdays prices. There is a job which updates each table over night. Yesterdays prices is a copy of todays before it gets updated.
I am trying to create a table which shows the differences between the tables.
To do this I am using a full outer join. I am filtering down my criteria to make it faster as both tables are over 48 million rows.
My current code is like this.
WITH differ AS
(
SELECT
tAP.CustomerID, tAP.ProductID, yAP.CustomerID AS 'Yest_CustomerID', yAP.ProductID AS 'Yest_ProductID',
tAP.PDG, tAP.DiscPct1, tAP.DiscPct2,
yAP.DiscPct1 AS 'Yest_DiscPct1',
yAP.DiscPct2 AS 'Yest_DiscPct2',
CONVERT(DECIMAL(18,2),tAP.DiscPct1 - yAP.DiscPct1) AS 'DiscPct1_Difference',
CONVERT(DECIMAL(18,2),tAP.DiscPct2 - yAP.DiscPct2) AS 'DiscPct2_Difference',
tAP.internalSPANumber, yAP.internalSPANumber AS 'Yest_InternalSPANumber', tAP.SPAUniqueReference,
tAP.Project,
tAP.ExpiryDate,tAP.Subaddress, tAP.PriceType, yAP.PriceType AS 'Yest_PriceType', tAP.ListPrice,
tAP.NettPrice, yAP.NettPrice AS 'Yest_NettPrice',
CONVERT(DECIMAL(18,2),tAP.NettPrice- yAP.NettPrice) AS 'NettPrice_Difference'
FROM tbl_Prices tAP FULL OUTER JOIN tbl_Prices_Yesterday yAP ON tAP.CustomerId = yAP.CustomerID AND tAP.ProductID = yAP.ProductID
AND tAP.PDG = yAP.PDG AND tAP.Project = yAP.Project AND tAP.PriceType = yAP.PriceType
WHERE (((tAP.DiscPct1 <> yAP.DiscPct1)
OR (tAP.DiscPct2 <> yAP.DiscPct2)
OR (yAP.CustomerID IS NULL)
OR (tAP.CustomerID IS NULL)
OR (tAP.NettPrice <> yAP.NettPrice)
OR (tAP.InternalSPANumber <> yAP.InternalSPANumber))
AND
(
tAP.ProductID = '10238610' OR tAP.ProductID = '10238620'
OR tAP.ProductID = '10238621' OR tAP.ProductID = '10238687'
OR tAP.ProductID = '10238688' OR yAP.ProductID = '10238610'
OR yAP.ProductID = '10238620' OR yAP.ProductID = '10238621'
OR yAP.ProductID = '10238687' OR yAP.ProductID = '10238688')
)
)
SELECT * INTO tbl_Difference FROM differ
Anyway to make this faster?
Can you filter the 2 large tables before you try to join them using AND filter in your where?
WITH tAPcte AS
(
SELECT * -- fields you need
FROM tbl_Prices
WHERE ProductID IN ('10238610',
'10238620',
'10238621',
'10238687',
'10238688')
),
yAPcte AS
(
SELECT * -- fields you need
FROM tbl_Prices_Yesterday
WHERE ProductID IN ('10238610',
'10238620',
'10238621',
'10238687',
'10238688')
)
differ AS
(
SELECT
tAP.CustomerID, tAP.ProductID, yAP.CustomerID AS 'Yest_CustomerID', yAP.ProductID AS 'Yest_ProductID',
tAP.PDG, tAP.DiscPct1, tAP.DiscPct2,
yAP.DiscPct1 AS 'Yest_DiscPct1',
yAP.DiscPct2 AS 'Yest_DiscPct2',
CONVERT(DECIMAL(18,2),tAP.DiscPct1 - yAP.DiscPct1) AS 'DiscPct1_Difference',
CONVERT(DECIMAL(18,2),tAP.DiscPct2 - yAP.DiscPct2) AS 'DiscPct2_Difference',
tAP.internalSPANumber, yAP.internalSPANumber AS 'Yest_InternalSPANumber', tAP.SPAUniqueReference,
tAP.Project,
tAP.ExpiryDate,tAP.Subaddress, tAP.PriceType, yAP.PriceType AS 'Yest_PriceType', tAP.ListPrice,
tAP.NettPrice, yAP.NettPrice AS 'Yest_NettPrice',
CONVERT(DECIMAL(18,2),tAP.NettPrice- yAP.NettPrice) AS 'NettPrice_Difference'
FROM tAPcte tAP FULL OUTER JOIN yAPcte yAP ON tAP.CustomerId = yAP.CustomerID AND tAP.ProductID = yAP.ProductID
AND tAP.PDG = yAP.PDG AND tAP.Project = yAP.Project AND tAP.PriceType = yAP.PriceType
WHERE (((tAP.DiscPct1 <> yAP.DiscPct1)
OR (tAP.DiscPct2 <> yAP.DiscPct2)
OR (yAP.CustomerID IS NULL)
OR (tAP.CustomerID IS NULL)
OR (tAP.NettPrice <> yAP.NettPrice)
OR (tAP.InternalSPANumber <> yAP.InternalSPANumber))
)
SELECT * INTO tbl_Difference FROM differ

How to join three tables?

SELECT
PC_SL_ACNO, -- DB ITEM
SLNAME, -- ACCOUNT NAME:
SL_TOTAL_AMOUNT -- TOTAL AMOUNT:
FROM GLAS_PDC_CHEQUES
WHERE PC_COMP_CODE=:parameter.COMP_CODE
AND pc_bank_from = :block02.pb_bank_code
AND pc_due_date between :block01.date_from
AND :block01.date_to
AND nvl(pc_discd,'X') IN(‘X’, 'R')
GROUP BY
pc_comp_code, pc_sl_ldgr_code, pc_sl_acno
ORDER BY pc_sl_acno
ACCOUNT NAME:
BEGIN
SELECT COAD_PTY_FULL_NAME INTO :BLOCK03.SLNAME
FROM GLAS_PTY_ADDRESS,GLAS_SBLGR_MASTERS
WHERE SLMA_COMP_CODE = :PARAMETER.COMP_CODE
AND SLMA_ADDR_ID = COAD_ADDR_ID
AND SLMA_ADDR_TYPE = COAD_ADDR_TYPE
AND SLMA_ACNO = :BLOCK03.PC_SL_ACNO
AND SLMA_COMP_CODE = COAD_COMP_CODE;
EXCEPTION WHEN OTHERS THEN NULL;
END;
TOTAL AMOUNT:
BEGIN
SELECT SUM(PC_AMOUNT) INTO :SL_TOTAL_AMOUNT
FROM GLAS_PDC_CHEQUES
WHERE PC_DUE_DATE BETWEEN :BLOCK01.DATE_FROM AND :BLOCK01.DATE_TO
AND PC_BANK_FROM = :block02.PB_BANK_CODE
AND PC_SL_ACNO = :BLOCK03.PC_SL_ACNO
AND NVL(PC_DISCD,'X') = 'R'
AND PC_COMP_CODE = :PARAMETER.COMP_CODE;
EXCEPTION WHEN OTHERS THEN :block03.SL_TOTAL_AMOUNT := 0;
END;
How can I join the three tables?
You'll have to adjust depending on precisely what criteria and required fields you have for your query or queries.
SELECT
c.PC_SL_ACNO,
a.COAD_PTY_FULL_NAME,
SUM(c.PC_AMOUNT)
FROM
GLAS_PDC_CHEQUES c
LEFT JOIN
GLAS_SBLGR_MASTERS m
ON ( c.PC_SL_ACNO = m.SLMA_ACNO
AND c.PC_COMP_CODE = m.SLMA_COMP_CODE
)
LEFT JOIN
GLAS_PTY_ADDRESS a
ON ( m.SLMA_ADDR_ID = a.COAD_ADDR_ID
AND m.SLMA_COMP_CODE = a.COAD_COMP_CODE
AND m.SLMA_ADDR_TYPE = a.COAD_ADDR_TYPE
)
WHERE
c.PC_COMP_CODE = :PARAMETER.COMP_CODE
AND c.PC_SL_ACNO = :BLOCK03.PC_SL_ACNO
AND c.PC_BANK_FROM = :BLOCK02.PB_BANK_CODE
AND NVL(c.PC_DISCD,'X') IN (‘X’, 'R')
AND c.PC_DUE_DATE BETWEEN :BLOCK01.DATE_FROM AND :BLOCK01.DATE_TO
GROUP BY
c.PC_SL_ACNO, -- not sure which grouping exactly you need.
a.COAD_PTY_FULL_NAME
ORDER BY
c.PC_SL_ACNO
I notice that in the first query you have pc_comp_code as a search criterion, and on the leading edge of your grouping - is that what you need?
This is a bit of an 'estimate' due to the enigmatic nature of your question!