I have an complex update procedure and now need to add another validation condition
to the process to make sure I'm getting the correct addr for the correct mtl_addr_div and asi_division. I just add a field to the parms table called Division, and on the MTD_INVOICE
there is a field called asi_division these are the key to the new update. The code at the bottom is what I'm trying to add into this procedure, or maybe you have a better way of doing what I'm try to accomplish..
Sorry formatting I tried too but my first post
THanks
;WITH Ranked AS (
SELECT H.ship_cust_nbr, H.Invoice_Nbr, D.Prime_Line_Nbr,d.gl_division, D.Mtl_Type,D.Mtl_Addr_Price,c1.mtl_addr_pricelist,h.asi_division,c1.mtl_addr_division,
COALESCE(C1.mtl_addr_Adder+C1.Mtl_Addr_ExtAddr, C2.mtl_addr_adder+C2.Mtl_Addr_ExtAddr) AS new_price,
COALESCE(C1.mtl_addr_StartDate, C2.mtl_addr_StartDate) AS start_date,
ROW_NUMBER() OVER(PARTITION BY H.Ship_Cust_nbr, D.Mtl_Type,D.Invoice_Nbr,D.Prime_Line_Nbr,cm.cm_curr
ORDER BY CASE WHEN C1.mtl_addr_adder IS NOT NULL
THEN 1
ELSE 2
END, COALESCE(C1.mtl_addr_adder, C2.mtl_addr_adder)) AS rk
FROM dbo.MTD_INVOICE AS H
JOIN dbo.MTD_INV_LINE_ITEM AS D
on h.company = d.company
and h.gl_division = d.gl_division
and h.acct_year = d.acct_year
and h.acct_month = d.acct_month
and h.Invoice_nbr = d.Invoice_nbr
and d.Prod_Line in ('xx6','xx8')
and not h.order_type = 'i'
join cm_mstr as cm
on h.ship_cust_nbr = cm.cm_addr
LEFT JOIN parms.dbo.mtl_addr_price AS C1
ON H.ship_cust_nbr = C1.mtl_addr_custcode
AND D.Mtl_Type = C1.mtl_addr_mtltype
and cm.cm_curr = c1.mtl_addr_currency
AND H.Invoice_Date BETWEEN C1.mtl_addr_StartDate AND COALESCE(C1.mtl_addr_EndDate, CURRENT_TIMESTAMP)
LEFT JOIN parms.dbo.mtl_addr_price AS C2
ON H.ship_cust_nbr = C2.mtl_addr_custcode
AND D.Mtl_Type = C2.mtl_addr_MtlType
AND D.Mtl_Type = C1.mtl_addr_mtltype
and cm.cm_curr = c1.mtl_addr_currency
AND H.Invoice_Date >= C2.mtl_addr_StartDate
AND NOT EXISTS(SELECT *
FROM parms.dbo.mtl_addr_price AS C3
WHERE C3.mtl_addr_custcode = C2.mtl_addr_custcode
AND C3.mtl_addr_MtlType = C2.mtl_addr_MtlType
and c3.mtl_addr_currency = c2.mtl_addr_currency
AND C3.mtl_addr_StartDate > C2.mtl_addr_StartDate
AND C3.mtl_addr_StartDate <= H.Invoice_Date))
UPDATE MTD_INV_LINE_ITEM
SET Mtl_Addr_Price = new_price
output r.ship_cust_nbr,
inserted.invoice_nbr,inserted.prime_line_nbr,
inserted.Prod_line,inserted.Mtl_Type,inserted.mtl_addr_Price,r.mtl_addr_pricelist,r.mtl_addr_division,r.ASI_DIVISION
into dbo.SdtlLOG_Daily(CustNbr,InvoiceNbr,InvLine,Prodline,MtlCode,saddr,PriceList,divused,channel)
FROM MTD_INV_LINE_ITEM AS D
JOIN Ranked AS R
ON D.Invoice_Nbr = R.Invoice_Nbr
AND D.prime_line_nbr = R.prime_line_nbr
-- AND cm.cm_curr = R.cm_curr
AND D.Mtl_Type = R.Mtl_Type
AND R.rk = 1
AND R.start_date IS NOT NULL