· 9 years ago · Oct 14, 2016, 03:26 PM
1USE [EDW_ODS]
2GO
3/****** Object: StoredProcedure [dbo].[AdHocReport39] Script Date: 10/14/2016 10:24:35 AM ******/
4SET ANSI_NULLS ON
5GO
6SET QUOTED_IDENTIFIER ON
7GO
8
9/* =========================================================================================================================
10 CREATED BY: KRAVVYA 12-27-2007
11 PURPOSE: Returns Report Data
12 NOTE: Based on the list of COServices in #COService_Search, will collect AdHoc report data
13 based on user's pre-defined criteria
14 Changes:
15 02/07/2008 - Replaced procedure with the one from CHR441\C. Backed up current
16 procedure @ Backup_AdHocReport
17 09/04/2008 - GANASAD - Changed CHRSubOrderNumber to CustomerOrderNumber and added
18 SourceTypeID
19 09/29/2008 - GANASAD - Updated money tables to use EXISTS for #UserCCodes instead
20 of a join to remove duplicates
21 01/08/2010 - SIPEBAR - Renamed DispatchCarrierName to be TenderedToCarrierName and
22 DispatchedDate to be TenderedToCarrierDate.
23 02/04/2011 - SUGGMIC - Modified COSAlert query to avoid 'Truck order not used' causing duplicate column name
24 02/15/2011 - SUGGMIC - Added Original NMFC
25 03/01/2011 - ANDERMIC - Added LoadHotY, @ProcessLoad
26 04/20/2011 - SUGGMIC - Added logic to replace custrefnum from ',' to ', '
27 06/11/2011 - SUGGMIC - Changed code from varchar to nvarchar for unicode, NOT VERSIONED because it goes with DW deployment
28 07/25/2011 - OKOASET - Added 'DestRampETADate' to @ProcessLFUDates column
29 08/02/2011 - OKOASET - Versioned report to AdHocReport7. Added searching by @datetype EstimatedPickupDate and EstimatedDeliveryDate
30 08/16/2011 - ANDERMIC- Added Support for CustomEquipmentType (from CustomEquipmentTypeID/CETID)
31 09/06/2011 - SUGGMIC- Updated temp table defintions for DimLocation unicode support
32 10/17/2011 - OKOASET - Added EmptyReturnDate,LastFreeDate Update SP to vs 9
33 12/29/2011 - andermic - Version 10, SpoofBookedFlag
34 07/10/2011 - OKOASET - Version 11 Added Purchase Order Fields Release 6.5
35 08/07/2012 - Added joins to SPOrder to filter our Master loads.
36 08/22/2012 - OKOASET - Version 12, PO bug fixes
37 10/17/2012 - OKOASET - Versioned for 7.1 added 'Agriculture Hold Date','FDA Exam' (version 13)
38 10/17/2012 - ANDERMIC - multileg (version 13)
39 12/07/2012 - REESFRA - changed COItem Class so that actual is used if there, else
40 01/22/2013 - RESCEMI - Added Receiving Booking Date field (Version 15, Release 7.4)
41 04/22/2013 - HABECHR - added Orion Notes
42 05/2/2013 - suggmic - added ML logic
43 12/04/2013 - okoaset - cast CHRNumber to string in final select statement. I am doing so, because of data merge in code beween this result set and
44 PXH adhoc result set. per requirement, PHX HbL Number with is a string should be displayed in CHRNumber column.
45 12/12/2013 - legejoh - changes made by Jeremy to improve performance of PO reports, changes marked with marked with Jeremy Dixon change 12/11/2013
46 12/15/2013 - suggmic - changed logic for GFS dates to pull max instead of min dates for destination fields.
47 01/31/2014 - suggmic - added logic to break down charges for ML
48 03/01/2014 - suggmic - added fix for duplicate charges for warehouse restrictions
49 03/10/2014 - suggmic - added Min/Max expected weight @ item level, split ISF ID # and ISF Date
50 04/10/2014 - okoaset - added weight Actual Weight issue. change from join from inner to left.
51 08/14/2014 - rescemi - changed terminal and ramp dates to only display the final terminal/ramp's dates
52 08/26/2014 - okoaset - change logic for ItemSummary and Item level report per ExcludeFromBL and ExcludeFromAES on COItem table
53 09/23/2014 - rescemi - fixed terminal and ramp logic
54 12/04/2014 - jewebra - Add logic to handle items that have both ExcludeFromBL and ExcludeFromAES checked
55 04/22/2015 - oneimas - Fixing InnerPackOriginalQuantity and InnerPackQuantity to map to the correct columns
56 04/22/2015 - oneimas - Fixing BuyerID to map to correct reference type name "Buyer Identifier"
57 07/02/2015 - oneimas - Including KeyLocationID with #SPODLocationDates
58 08/20/2015 - oneimas - Doing the join with #SPODLocationDates on OrigSPODKeyLocationID and DestSPODKeyLocationID
59 08/28/2015 - rescemi - Adding GFO changes
60 09/08/2015 - oneimas - Adding Invoice column ReceivedAmount and InvoiceTotal
61 11/04/2015 - oneimas - Fixing duplicate #Misc records from missing IntlCHRRole on insert
62 11/04/2015 - rescemi - Adding index to #UnpivotedFUDate to fix PO issues
63 11/17/2015 - oneimas - Adding join on COSGroup to account for change to COrder
64 12/21/2015 - menaron - Added work around to filter out multileg records that do not meet the original report criteria
65 02/11/2016 - habechr - Added OrderedSpace + fix Entered By Bug
66 03/09/2016 - rescemi - Fixing Vessel/Voyage & Customer Reference Numbers for GFO
67 03/22/2016 - rescemi - Changing "Buyer Identifier" to "Buyer ID #"
68 06/09/2016 - rescemi - Placeholder (Version 36)
69 07/06/2016 - goblnic - Upping column size to fit larger dataset
70 07/14/2016 - spitkyl - Changed data type of #Customs.BrokerName to NVARCHAR(250)
71 08/23/2016 - PHILBEN - Add reference number CIN
72 08/23/2016 - HABECHR - Add EDI Reference Numbers Section
73 09/01/2016 - HAGEAAR - delete records from #Invoice where InvoiceReleaseDate outside of @StartDate & @EndDate
74 09/09/2016 - HAGEAAR - Fix error caused by long Accessorial Charge Descriptions
75 09/12/2016 - RESCEMI - adding new invoice joins for CustomsCOServiceID
76 10/5/2016 - HABECHR - Service Release on this version for requirement changes
77 ========================================================================================================================= */
78
79ALTER PROCEDURE [dbo].[AdHocReport39]
80(
81 @LogID INT
82)
83AS
84BEGIN
85 -- =========================================================================================================================
86 -- LINE NUMBERS:
87 --
88 -- Create Temp Tables:
89 --
90 -- Load #Row and #Column Tables:
91 -- Load variables with report criteria:
92 -- Load #Row with detail for found COServices:
93 -- Load #Row table with related data if user selected Summary OD Pair option:
94 -- Load #Row table with related data if user selected Summary Container option:
95 -- Update #Row table with First and Last Stop Numbers:
96 -- Build RecordIDs for #Row table:
97 --
98 -- Build #SummaryCore Table:
99 --
100 -- Figure out what temp tables to populate:
101 -- Populate Alerts:
102 -- Populate ClosedAlerts:
103 -- Populate Payers:
104 -- Populate SpecialInstructions:
105 -- Populate CustomerLocations:
106 -- Populate Misc:
107 -- Populate MiscDates:
108 -- Populate MiscEstDates:
109 -- Populate InterLocations:
110 -- Populate FUDates:
111 -- Populate LFUDates:
112 -- Populate Invoices:
113 -- Populate Items:
114 -- Populate ItemSummaries:
115 -- Populate ItemSummaryTexts:
116 -- Note about Ref, ItemRef, and Charges:
117 -- Populate Comments:
118 -- Populate COServices:
119 -- Populate CHRStatuses:
120 -- Populate LastInvoices:
121 -- Populate LastEvents:
122 -- Populate SPOrders:
123 -- Populate SPOrderIntls:
124 -- Populate SPOrderOthers:
125 -- Populate Customs:
126 -- Populate PoolCrossLocations:
127 -- Populate PoolCrossLocationDates:
128 --
129 -- Build temp tables required for dates:
130 --
131 -- Load Temp tables with Data:
132 -- Load #Alerts:
133 -- Load #ClosedAlerts:
134 -- Load #Payers:
135 -- Load #SpecialInstructions:
136 -- Load #CustomerLocation:
137 -- Load #MISC:
138 -- Load #MiscDate:
139 -- Load #MiscEstDate:
140 -- Load #InterLocation:
141 -- Load #FUDate:
142 -- Load #LFUDate:
143 -- Load #Invoice:
144 -- Load #Item:
145 -- Load #ItemSummary:
146 -- Load #DriverTixSummary:
147 -- Load #ItemSummaryText:
148 -- Load #Ref:
149 -- Load #ItemRef:
150 -- Load Charges:
151 -- #AccessorialChargeDescription:
152 -- #FreightCharge:
153 -- #AccessorialOtherCharge:
154 -- #TotalCharge:
155 -- #EndCustFreightCharge:
156 -- #EndCustAccessorialCharge:
157 -- #EndCustTotalCharges:
158 -- #SourceCurrencyCode:
159 -- Load #Comment:
160 -- Load #COService:
161 -- Load #CHRStatus:
162 -- Load #LastInvoice:
163 -- Load #Alert:
164 -- Load #ClosedAlert:
165 -- Load #LastEvent:
166 -- Load #SPOrder:
167 -- Load #SPOrderIntl:
168 -- Load #SPOrderOther:
169-- Load #Customs:
170 -- Load #PoolCrossLocation:
171 -- Load #PoolCrossLocationDate:
172 --
173 -- Build @SQL:
174 --
175-- Execute @SQL:
176 --
177 -- Return Other Result Sets:
178 -- =========================================================================================================================
179
180 SET NOCOUNT ON
181
182 -- =====================================================================================================================
183 -- CREATE TEMP TABLES
184 -- =====================================================================================================================
185
186 --PRINT 'Creating tables'
187
188 --We will return Payers as a separate resultset
189
190CREATE TABLE #TEMP_CHARGES
191(
192 RecordID INT,
193 ProcessRollUp BIT,
194 ProcessBreakdown BIT,
195 MoneyType CHAR(10),
196 [Description] NVARCHAR(256),
197 Amount MONEY,
198 AccessorialFlg BIT,
199 FinancialType CHAR(10),
200 SourceCurrencyCode VARCHAR(50)
201)
202
203 CREATE TABLE #Payer
204 (
205 PayerNumber INT
206 ,Payer_RecordID INT
207 ,PayerName VARCHAR(50)
208 ,PayerAddress1 VARCHAR(50)
209 ,PayerAddress2 VARCHAR(50)
210 ,PayerCity VARCHAR(225)
211 ,PayerState CHAR(100)
212 ,PayerZip VARCHAR(10)
213 ,PayerLocationID VARCHAR(50)
214 ,PartyNumber INT
215 )
216
217 -- 09/16/2008 GANASAD Added for LXSI
218 CREATE TABLE #MethodOfPayment
219 (
220 MethodOfPayment_RecordID INT
221 ,MethodOfPayment VARCHAR(25)
222 )
223
224 -- no need to populate if summary. Part of the main resultset
225 CREATE TABLE #SpecialInstructions
226 (
227 SpecialInstructions_RecordID INT
228 ,OrigSpecialInstructions VARCHAR(MAX)
229 ,DestSpecialinstructions VARCHAR(MAX)
230 )
231
232 CREATE TABLE #StopNums
233 (
234 StopNums_RecordID INT,
235 StopNums VARCHAR(100)
236)
237
238 -- part of the main resultset. Need to update data to handle summary
239 CREATE TABLE #CustomerLocation
240 (
241 CustomerLocation_RecordID INT
242 ,OriginStopNumber INT -- DO NOT SHOW
243 ,DestStopNumber INT -- DO NOT SHOW
244 ,OrigName NVARCHAR(200)
245 ,OrigAddress1 NVARCHAR(100)
246 ,OrigAddress2 NVARCHAR(100)
247 ,OrigCity NVARCHAR(100)
248 ,OrigState NVARCHAR(100)
249 ,OrigCountry NVARCHAR(100)
250 ,OrigZip NVARCHAR(20)
251 ,OrigAirportCode VARCHAR(5) -- 09/17/2008 GANASAD LXSI
252 ,OrigLocationID VARCHAR(80)
253,DestName NVARCHAR(200)
254 ,DestAddress1 NVARCHAR(100)
255 ,DestAddress2 NVARCHAR(100)
256 ,DestCity NVARCHAR(100)
257 ,DestState NVARCHAR(100)
258 ,DestCountry NVARCHAR(100)
259 ,DestZip NVARCHAR(20)
260 ,DestLocationID VARCHAR(80)
261 ,DestAirportCode NVARCHAR(5) -- 09/17/2008 GANASAD LXSI
262 )
263
264 --We will return #MISC as a separate resultset
265 CREATE TABLE #MISC
266 (
267 MISC_RecordID INT
268 ,CustomerName VARCHAR(255) --CustomerParty
269 ,ShipperName VARCHAR(255)
270 ,ConsigneeName VARCHAR(255)
271 ,VendorName VARCHAR(255)
272 ,ImporterOfRecord VARCHAR(255)
273 ,Buyer VARCHAR(255)
274 --,EstimatedPickupDate INT -- Moved to MiscDate: join different tables
275 --,EstimatedDeliveryDate INT -- Moved to MiscDate: join different tables
276 --,EnterDate INT -- Moved to MiscDate: join different tables
277 --,CloseDate INT -- Moved to MiscDate: join different tables
278 --,DocumentTrackingDate INT -- Moved to MiscDate: join different tables
279 --,DeliveryOrderCreatedDate INT -- Moved to MiscDate: join different tables
280 --,TruckloadActivityDate INT -- Moved to MiscDate: join different tables
281 ,OrderedBy VARCHAR(255)
282 ,EnteredBy VARCHAR(255)
283 ,MasterLinehaulName VARCHAR(255) -- OLH
284 )
285
286 CREATE TABLE #Compliance
287 (
288 Compliance_RecordID INT,
289 NonComplianceCode VARCHAR(50),
290 NonComplianceCodeReason VARCHAR(50),
291 DeleteFlg BIT
292 )
293
294-- CREATE TABLE #POD
295-- (
296-- POD_RecordID INT,
297-- OceanAirProofOfDeliveryDate VARCHAR(25)
298-- )
299
300 CREATE TABLE #MiscDate
301 (
302 MiscDate_RecordID INT
303-- ,EnterDate INT
304 ,CloseDate INT
305 ,DocumentTrackingDate INT
306 ,DeliveryOrderCreatedDate INT
307 ,TruckloadActivityDate INT
308 ,EstimatedPickupDate INT
309 ,EstimatedDeliveryDate INT
310 ,Overwrite BIT
311 )
312
313 -- part of the main resultset. Need to update data to handle summary
314 -- TODO Do the numbers
315 CREATE TABLE #InterLocation
316 (
317 InterLocation_RecordID INT
318 ,OrigTerminalStopNumber INT
319 ,OrigTerminalName NVARCHAR(200)
320 ,OrigTerminalCity NVARCHAR(100)
321 ,OrigRampStopNumber INT
322 ,OrigRampName NVARCHAR(200)
323 ,OrigRampCity NVARCHAR(100)
324 ,LoadingPortStopNumber INT
325 ,LoadingPort NVARCHAR(200)
326 ,LoadingPortCountry NVARCHAR(20)
327 ,DischargePortStopNumber INT
328 ,DischargePort NVARCHAR(200)
329 ,DischargePortCountry NVARCHAR(20)
330 ,DestRampStopNumber INT
331 ,DestRampName NVARCHAR(200)
332 ,DestRampCity NVARCHAR(100)
333 ,DestTerminalStopNumber INT
334 ,DestTerminalName NVARCHAR(200)
335 ,DestTerminalCity NVARCHAR(100)
336 )
337
338CREATE TABLE #UnpivotedFUDate(
339 RecordID INT,
340 DateTimeType VARCHAR(100),
341 DateTimeValue INT
342 )
343
344 CREATE CLUSTERED INDEX IDX_C_UnpivotedFUDate ON #UnpivotedFUDate (RecordID)
345
346 -- part of the main resultset.
347 CREATE TABLE #FUDate
348 (
349 FUDate_RecordID INT
350 ,EnterDate INT
351 ,EnterTime INT
352 ,EarliestReqPickupDate INT
353 ,EarliestReqPickupTime INT
354 ,LatestReqPickupDate INT
355 ,LatestReqPickupTime INT
356 ,EarliestSchedPickupDate INT
357 ,EarliestSchedPickupTime INT
358 ,LatestSchedPickupDate INT
359 ,LatestSchedPickupTime INT
360 ,EarliestActualPickupDate INT
361 ,EarliestActualPickupTime INT
362 ,LatestActualPickupDate INT
363 ,LatestActualPickupTime INT
364 ,ShipperDropTrailerArrivalDate INT
365 ,ShipperDropTrailerArrivalTime INT
366 ,ShipperDropTrailerReadyDate INT
367 ,ShipperDropTrailerReadyTime INT
368 ,EarliestReqDeliveryDate INT
369 ,EarliestReqDeliveryTime INT
370 ,LatestReqDeliveryDate INT
371 ,LatestReqDeliveryTime INT
372 ,EarliestSchedDeliveryDate INT
373 ,EarliestSchedDeliveryTime INT
374 ,LatestSchedDeliveryDate INT
375 ,LatestSchedDeliveryTime INT
376 ,EarliestActualDeliveryDate INT
377 ,EarliestActualDeliveryTime INT
378 ,LatestActualDeliveryDate INT
379 ,LatestActualDeliveryTime INT
380 ,ConsigneeDropTrailerArrivalDate INT
381 ,ConsigneeDropTrailerArrivalTime INT
382 ,ConsigneeDropTrailerReadyDate INT
383 ,ConsigneeDropTrailerReadyTime INT
384 )
385
386 -- part of the main resultset.
387 CREATE TABLE #LFUDate
388 (
389 LFUDate_RecordID INT
390 ,OrigTerminalETADate INT
391 ,OrigTerminalArrivalDate INT
392 ,OrigTerminalArrivalTime INT
393 ,OrigTerminalDepartDate INT
394 ,OrigTerminalDepartTime INT
395 ,OrigRampCutOffDate INT
396 ,OrigRampCutOffTime INT
397,OrigRampArrivalDate INT
398 ,OrigRampArrivalTime INT
399 ,OrigRampRampedDate INT
400 ,OrigRampRampedTime INT
401 ,PortCutoffDate INT
402 ,OriginalPortETDDate INT
403 ,PortETDDate INT
404 ,OriginalPortETADate INT
405 ,PortETADate INT
406 ,ActualPortArrivalDate INT
407 ,ActualPortDepartDate INT
408 ,DestRampArrivalDate INT
409 ,DestRampArrivalTime INT
410 ,DestRampDeRampedDate INT
411 ,DestRampDeRampedTime INT
412 ,RailETADate INT
413 ,DestRampETADate INT
414 ,DestTerminalETADate INT
415 ,DestTerminalArrivalDate INT
416 ,DestTerminalArrivalTime INT
417 ,DestTerminalDepartDate INT
418 ,DestTerminalDepartTime INT
419 ,IMDLPromiseDate INT
420 ,EmptyReturnDate INT
421 ,LastFreeDate INT
422 )
423
424CREATE TABLE #TEMP_LFU_DATES (
425 RecordID INT,
426 DateType VARCHAR(50),
427 DateValue INT,
428 TimeValue INT,
429 DateBarTime VARCHAR(65),
430 AggregatedResult BIGINT
431)
432
433CREATE TABLE #TEMP_LFU_DATES_PIVOTED (
434 RecordID INT,
435 OrigTerminalETADate INT,
436 OrigTerminalArrivalDate INT,
437 OrigTerminalDepartDate INT,
438 OrigRampCutOffDate INT,
439 OrigRampArrivalDate INT,
440 OrigRampRampedDate INT,
441 PortCutoffDate INT,
442 OriginalPortETDDate INT,
443 PortETDDate INT,
444 OriginalPortETADate INT,
445 PortETADate INT,
446 ActualPortArrivalDate INT,
447 ActualPortDepartDate INT,
448 DestRampArrivalDate INT,
449 DestRampDeRampedDate INT,
450 RailETADate INT,
451 DestRampETADate INT,
452 DestTerminalETADate INT,
453 DestTerminalArrivalDate INT,
454 DestTerminalDepartDate INT,
455 IMDLPromiseDate INT,
456 EmptyReturnDate INT,
457 LastFreeDate INT
458)
459
460CREATE TABLE #TEMP_LFU_TIMES_PIVOTED (
461 RecordID INT,
462 OrigTerminalArrivalTime INT,
463 OrigTerminalDepartTime INT,
464 OrigRampCutOffTime INT,
465 OrigRampArrivalTime INT,
466 OrigRampRampedTime INT,
467 DestRampArrivalTime INT,
468 DestRampDeRampedTime INT,
469 DestTerminalArrivalTime INT,
470 DestTerminalDepartTime INT
471)
472
473 --separate resultset
474 CREATE TABLE #Invoice
475 (
476 Invoice_RecordID INT
477 ,InvoiceDate INT -- do we want int?
478 ,InvoiceNum VARCHAR(max)
479 ,CHRListBillNum BIGINT -- 05/06/2009 GANASAD Euro Invoices uses InvoiceNums as their List Bills, so changed from INT to BIGINT
480 ,InvoiceReleaseDate INT
481 ,InvoiceBalance MONEY
482 ,ReceivedAmount MONEY
483 ,InvoiceTotal MONEY
484 ,InvoiceStatus VARCHAR(25)
485 )
486
487 --main resultset
488 CREATE TABLE #Item
489 (
490 Item_RecordID INT
491 ,ItemID INT -- Not displayed? Bill can't find it in the tabs.
492 ,ExFactoryDate DATETIME -- Why not int?
493 ,ActualQuantity DECIMAL(19,0) -- 04/08/2008 GANASAD - removed decimal places
494 ,HazardousItem BIT
495 ,Class VARCHAR(50) -- 10/01/2008 GANASAD - Column in database is VARCHAR(50)
496 ,CommodityCategory VARCHAR(200)
497 ,[Value] DECIMAL(19,2) -- MONEY 04/17/2008 GANASAD
498 ,ExpectedQuantity DECIMAL(19,0) -- 04/08/2008 GANASAD - removed decimal places
499 ,[Weight] DECIMAL(19,2) -- 04/08/2008 GANASAD - 4 decimal places to 2
500 ,TempSensitive BIT
501 ,SKU VARCHAR(50)
502 ,Hot BIT
503 ,CustCommodityCode CHAR(15)
504-- ,HTCode VARCHAR(50) -- Moved to #ItemRef
505 ,Pallets DECIMAL(19,2) -- 04/08/2008 GANASAD - 4 decimal places to 2
506 ,UnitOfMeasure VARCHAR(50)
507 ,CustCommodityName VARCHAR(200)
508 ,DimensionalWeight DECIMAL(19,2) -- 04/08/2008 GANASAD - 4 decimal places to 2
509 ,PalletSpaces DECIMAL(19,2) -- 04/08/2008 GANASAD - 4 decimal places to 2
510 ,ItemDescription VARCHAR(500) -- 04/25/2008 GANASAD - There's one that's 307 characters long
511 ,ActualEDIPackagingCode VARCHAR(50)
512 ,ActualVolume DECIMAL(19,2) -- 04/08/2008 GANASAD - 4 decimal places to 2
513 ,InnerPack DECIMAL(19,2)
514 ,UnitsPerPallet DECIMAL(19,2)
515 ,MasterPack INT
516 ,ItemLength DECIMAL(19,4)
517 ,ItemWidth DECIMAL(19,4)
518 ,ItemHeight DECIMAL(19,4)
519 ,OriginalFreightClass VARCHAR(50)
520 ,OriginalPallets DECIMAL(19, 2)
521 ,OriginalPalletSpaces DECIMAL(19, 2)
522 ,OriginalQuantity DECIMAL(19, 0)
523 ,OriginalWeight DECIMAL(19, 2)
524 ,OriginalVolume DECIMAL(19, 2)
525 ,OriginalNMFC VARCHAR(50)
526 ,ExpectedMinWeight DECIMAL(19,4)
527 ,ExpectedMaxWeight DECIMAL(19,4)
528 )
529
530 CREATE TABLE #ItemFlatbed
531 (
532 ItemFlatbed_RecordID INT
533 ,Overdimensional BIT
534 ,EquipmentTypeCode VARCHAR(10)
535 ,TarpLength VARCHAR(10)
536 ,RequiredChains INT
537 ,RequiredStraps INT
538 ,CoilRacks INT
539 ,LoadingType VARCHAR(10)
540 ,ItemFlatbedID INT
541 )
542
543 --main resultset.
544 CREATE TABLE #ItemSummary
545 (
546 ItemSummary_RecordID INT
547 ,SummaryActualQuantity DECIMAL(19,0) -- 04/08/2008 GANASAD - removed decimal places
548 ,SummaryExpectedQuantity DECIMAL(19,0) -- 04/08/2008 GANASAD - removed decimal places
549 ,SummaryActualPallets DECIMAL(19,2) -- 04/08/2008 GANASAD - 4 decimal places to 2
550 ,SummaryExpectedPallets DECIMAL(19,2) -- 04/08/2008 GANASAD - 4 decimal places to 2
551 ,SummaryActualWeight DECIMAl(19,2) -- 04/08/2008 GANASAD - 4 decimal places to 2
552 ,SummaryExpectedMinWeight DECIMAL(19,2) -- 04/08/2008 GANASAD - 4 decimal places to 2
553 ,SummaryHazardous BIT
554 ,SummaryPalletSpaces DECIMAL(19,2) -- 04/08/2008 GANASAD - 4 decimal places to 2
555 ,SummaryExpectedMaxWeight DECIMAL(19,2) -- 04/08/2008 GANASAD - 4 decimal places to 2
556 ,SummaryVolume DECIMAL(19,2) -- 04/08/2008 GANASAD - 4 decimal places to 2
557 ,SummaryDimensionalWeight DECIMAL(19,2) -- 04/15/2008 GANASAD
558 ,SummaryChargeableWeight DECIMAL(19,2) -- 04/15/2008 GANASAD
559 ,SummaryUnitOfMeasure VARCHAR(50) -- 04/15/2008 GANASAD
560 ,SummaryHot BIT
561 ,SummaryInnerPack DECIMAL(19,2)
562 ,SummaryOverDimensional BIT
563 ,SummaryOriginalQuantity DECIMAL(19, 0)
564 ,SummaryOriginalPallets DECIMAL(19, 2)
565 ,SummaryOriginalPalletSpaces DECIMAL(19, 2)
566 ,SummaryOriginalWeight DECIMAL(19, 2)
567 ,SummaryOriginalVolume DECIMAL(19, 2)
568 )
569
570 CREATE TABLE #DriverTixSummary
571 (
572 DriverTixSummary_RecordID INT
573 ,SummaryDriverHeavyWeightTix DECIMAL(19,2)
574 ,SummaryDriverLightWeightTix DECIMAL(19,2)
575 )
576
577 --separate resultset
578 CREATE TABLE #ItemSummaryText
579 (
580 ItemSummaryText_RecordID INT
581 ,SummaryCommodity VARCHAR(2008)
582 ,SummaryDescription VARCHAR(2008)
583 ,DeleteFlg BIT
584 )
585
586CREATE CLUSTERED INDEX IDX_C_ItemSummaryText ON #ItemSummaryText (ItemSummaryText_RecordID, DeleteFlg)
587 -- ConfirmationNumber,
588 -- CustRefNum,
589 -- PayerRefNum
590 -- CarrierProNum,
591 -- ShipperReference,
592 -- OrderNumber,
593 -- CustLoadNum,
594 -- MBOL,
595 -- HBOL,
596 -- SubHBOL,
597 -- MasterPO,
598 -- SSLineBOL
599 -- PickupNum,
600 -- DeliveryNum,
601 -- BOL
602 --separate resultsets
603 CREATE TABLE #Ref
604 (
605 Ref_RecordID INT
606 ,ReferenceType VARCHAR(50)
607 ,ReferenceSubType VARCHAR(50)
608 ,ReferenceNumber NVARCHAR(4000)
609 ,DeleteFlg BIT
610 )
611
612 CREATE CLUSTERED INDEX INX_REF_RecordID ON #Ref(Ref_RecordID)
613
614 -- UPC,
615 -- NMFC,
616 -- CustSpecific1,
617 -- CustSpecific2,
618 -- ProductCode,
619 -- PLU,
620 -- EAN,
621 -- HTCode
622 -- separate resultsets
623 CREATE TABLE #ItemRef
624 (
625 ItemRef_RecordID INT
626 ,ItemRef_ItemID INT
627 ,ItemReferenceType VARCHAR(50)
628 ,ItemReferenceSubType VARCHAR(50)
629 ,ItemReferenceNumber NVARCHAR(2008)
630 ,ItemDeleteFlg BIT
631 )
632
633 -- need to have unique column names across charges tables for pivots to work
634 --main resultset.
635 CREATE TABLE #AccessorialChargeDescription
636 (
637 AccessorialChargeDescription_RecordID INT
638 ,MoneyType CHAR(10)
639 ,Description VARCHAR(256)
640 ,Amount DECIMAL(10,2)
641 ,AccessorialChargeFinancialType CHAR(10)
642 )
643
644 --main resultset.
645 CREATE TABLE #FreightCharge
646 (
647 FreightCharge_RecordID INT
648 ,FreightCharge DECIMAL(10,2) -- MONEY 04/17/2008 GANASAD
649 )
650
651 CREATE TABLE #AgentFee
652 (
653 AgentFee_RecordID INT,
654 AgentFee DECIMAL(10,2)
655 )
656
657 --main resultset.
658 CREATE TABLE #AccessorialOtherCharge
659 (
660 AccessorialOtherCharge_RecordID INT
661 ,AccessorialOtherCharge DECIMAL(10,2) -- MONEY 04/17/2008 GANASAD
662 )
663
664 --main resultset.
665 CREATE TABLE #TotalCharge
666 (
667 TotalCharge_RecordID INT
668 ,TotalCharges DECIMAL(10,2) -- MONEY 04/17/2008 GANASAD
669 )
670
671 --main resultset.
672 CREATE TABLE #EndCustFreightCharge
673 (
674 EndCustFreightCharge_RecordID INT
675 ,EndCustFreightCharge DECIMAL(10,2) -- MONEY 04/17/2008 GANASAD
676 )
677
678 --main resultset.
679 CREATE TABLE #EndCustAccessorialCharge
680 (
681 EndCustAccessorialCharge_RecordID INT
682 ,EndCustAccessorialCharge DECIMAL(10,2) -- MONEY 04/17/2008 GANASAD
683 )
684
685 --main resultset.
686 CREATE TABLE #EndCustTotalCharges
687 (
688 EndCustTotalCharges_RecordID INT
689 ,EndCustTotalCharges DECIMAL(10,2) -- MONEY 04/17/2008 GANASAD
690 )
691
692 --main resultset.
693 CREATE TABLE #SourceCurrencyCode
694 (
695 SourceCurrencyCode_RecordID INT
696 ,SourceCurrencyCode CHAR(10)
697 )
698
699
700 -- no need to populate if summary. Part of the main resultset
701 CREATE TABLE #Comment
702 (
703 Comment_RecordID INT
704 ,Comment VARCHAR(MAX)
705 ,DeleteFlg BIT
706 )
707
708 -- Part of the main resultset summary: for intl show primary loads's service. For domestic show last sevice data. Sum up Charge columns.
709 CREATE TABLE #COService
710 (
711 COService_RecordID INT
712 ,ActualMode VARCHAR(15)
713 ,Expedited BIT
714 ,ExpeditedReason VARCHAR(50)
715 ,InboundStatus VARCHAR(50)
716 --,NonComplianceCode VARCHAR(50)
717 --,NonComplianceCodeReason VARCHAR(50)
718 ,FinancialCondition VARCHAR(15)
719 ,BaselineCharge DECIMAL(10,2) -- MONEY 04/17/2008 GANASAD
720 ,NonConsolidationCharge DECIMAL(10,2) -- MONEY 04/17/2008 GANASAD -- Current
721 ,CHRStatus VARCHAR(75) -- Put back in here
722 ,RoutedShipments VARCHAR(10)
723 ,ServiceLevel VARCHAR(50) -- 09/16/2008 GANASAD LXSI
724 --,ReceivedBy VARCHAR(50) -- 09/16/2008 GANASAD LXSI
725 --,PiecesDelivered VARCHAR(25) -- 09/16/2008 GANASAD LXSI
726 --,DeclaredValue MONEY -- 09/16/2008 GANASAD LXSI
727 ,Mode VARCHAR(15)
728 ,OrderMode VARCHAR(15)
729 ,LoadMode VARCHAR(512)
730 )
731
732/*NEW OR CHANGED Jeremy Dixon 11/2013*/
733 CREATE TABLE #COService_Capture
734 (
735 COService_RecordID INT
736 ,ActualMode VARCHAR(15)
737 ,Expedited BIT
738 ,ExpeditedReason VARCHAR(50)
739 ,InboundStatus VARCHAR(50)
740 ,FinancialCondition VARCHAR(15)
741 ,BaselineCharge DECIMAL(10,2)
742 ,NonConsolidationCharge DECIMAL(10,2)
743 ,CHRStatus VARCHAR(75)
744 ,RoutedShipments VARCHAR(10)
745 ,ServiceLevel VARCHAR(50)
746 ,Mode VARCHAR(15)
747 ,OrderMode VARCHAR(15)
748 ,LoadMode VARCHAR(512)
749 )
750 -- Part of the main resultset
751 CREATE TABLE #LastInvoice
752 (
753 LastInvoice_RecordID INT
754 ,Invoiced BIT
755 ,LastInvoiceDate INT
756 )
757
758 --If multiple of same type only include latest one. Only Include Active alerts
759 --main resultset
760 CREATE TABLE #Alert
761 (
762 Alert_RecordID INT
763 --,ShipmentAlerts
764 ,EnteredDate VARCHAR(50)
765 ,TheDate SMALLDATETIME -- For internal use
766 ,Description VARCHAR(5000) -- GANASAD Used to be 255, 5000 to handle EU data
767 ,ActiveFlg BIT -- For internal use
768 )
769
770-- CREATE TABLE #ClosedAlert
771-- (
772-- ClosedAlert_RecordID INT
773-- ,EnteredDate SMALLDATETIME
774-- ,Description VARCHAR(255)
775-- )
776
777 --main resultset
778 CREATE TABLE #LastEvent
779 (
780 LastEvent_RecordID INT
781 ,LastEvent VARCHAR(500)
782)
783
784 -- 04/15/08 GANASAD
785 CREATE TABLE #LastIMDLEvent
786 (
787 LastIMDLEvent_RecordID INT
788 ,LastIMDLEvent VARCHAR(255)
789 )
790
791 --separate resultset
792 CREATE TABLE #SPOrder
793 (
794 SPOrder_RecordID INT
795 ,Conveyance VARCHAR(1000)
796 ,ContractNum VARCHAR(500)
797 ,BookingNum VARCHAR(500)
798 ,BookingDate INT
799 ,CarrierName VARCHAR(500)
800 ,EquipmentType VARCHAR(500)
801 ,TractorNum VARCHAR(500)
802 ,TrailerNum VARCHAR(500)
803 ,TrailerSize VARCHAR(100)
804 ,DeleteFlg BIT
805 ,AirLineCarrier VARCHAR(500)
806 ,FlightNumber VARCHAR(500)
807 )
808
809
810 CREATE CLUSTERED INDEX idx_C_SPOrderTempTable ON #SPOrder
811 (SPOrder_RecordID)
812
813 CREATE TABLE #SPOrderIntl
814 (
815 SPOrderIntl_RecordID INT
816 ,ContainerNumber VARCHAR(2000)
817 ,ContainerType VARCHAR(500)
818 ,SummContainerNumber VARCHAR(2000)
819 ,SummContainerType VARCHAR(100) -- ContainerType size is 500
820 ,DeleteFlg BIT
821 )
822
823 CREATE CLUSTERED INDEX INX_SPorderIntl_ContainerNumber ON #SPOrderIntl(SPOrderIntl_RecordID, ContainerNumber)
824
825
826
827 --separate resultset
828 -- Sadhana: split from #SPOrder because we have to join on
829 -- completely different tables for these columns.
830 CREATE TABLE #SPOrderOther
831 (
832 SPOrderOther_RecordID INT
833-- ,LTLSCAC CHAR(10) -- 10/01/2008 GANASAD Moved to #SCAC
834 ,DeliveryCarrierName VARCHAR(100)
835-- ,DispatchCarrierName VARCHAR(100) -- Renamed TenderedToCarrierName
836 ,TenderedToCarrierName VARCHAR(100)
837 )
838
839 -- 10/01/2008 GANASAD
840 CREATE TABLE #SCAC
841 (
842 SCAC_RecordID INT
843 ,LTLSCAC VARCHAR(100) -- 10/02/2008 GANASAD Good for ~9 carriers
844 )
845
846 --main resultset
847 CREATE TABLE #Customs
848 (
849 Customs_RecordID INT
850 ,ITNum VARCHAR(500)
851 ,SSLReleaseDate SMALLDATETIME
852 ,EntryLocation VARCHAR(650)
853 ,OGAReleaseDate SMALLDATETIME
854 ,ReceiptDocsDate VARCHAR(500)
855 ,ITLocation VARCHAR(650)
856 ,EntryDate SMALLDATETIME
857 ,ExamRequiredDate SMALLDATETIME
858-- ,DispatchedDate SMALLDATETIME -- Renamed TenderedToCarrierDate
859 ,TenderedToCarrierDate SMALLDATETIME
860 ,FDAEntry VARCHAR(500)
861 ,ITDate SMALLDATETIME
862 ,EntryNum VARCHAR(200)
863 ,CustomsHoldDate SMALLDATETIME
864 ,TurnedOverDate SMALLDATETIME
865 ,FDAReqDate VARCHAR(500)
866 ,ReleaseDate SMALLDATETIME
867 ,BrokerName NVARCHAR(250)
868 ,OGAHoldDate SMALLDATETIME
869 ,Notes VARCHAR(2550)
870 ,FDASubmitDate VARCHAR(500)
871 ,DeleteFlg BIT
872 ,ISFID VARCHAR(2550) -- GANASAD Keeping consistent with the lengths in INSERT
873 ,ISFDate VARCHAR(2550)
874 ,DeclaredValue MONEY
875 )
876
877 -- main resultset
878 CREATE TABLE #PoolCrossLocation
879 (
880 PoolCrossLocation_RecordID INT
881 ,PoolpointName NVARCHAR(200)
882 ,PoolpointCity NVARCHAR(100)
883 ,PoolpointState NVARCHAR(100)
884 ,CrossDockName NVARCHAR(200)
885 ,CrossDockCity NVARCHAR(100)
886 ,CrossDockState NVARCHAR(100)
887 )
888
889 -- Sadhana: split from #PoolCrossLocation because we have to join
890 -- different tables and do different processing (unpivoting) to
891 -- get these columns.
892 -- main resultset
893CREATE TABLE #PoolCrossLocationDate
894 (
895 PoolCrossLocationDate_RecordID INT
896 ,PoolpointSchedArrivalDate INT
897 ,PoolpointSchedArrivalTime INT
898 ,PoolpointSchedDepartDate INT
899 ,PoolpointSchedDepartTime INT
900 ,PoolpointActualArrivalDate INT
901 ,PoolpointActualArrivalTime INT
902 ,PoolpointActualDepartDate INT
903 ,PoolpointActualDepartTime INT
904 ,CrossDockArrivalDate INT
905 ,CrossDockArrivalTime INT
906 ,CrossDockSchedDepartDate INT
907 ,CrossDockSchedDepartTime INT
908 ,CrossDockActualDepartDate INT
909 ,CrossDockActualDepartTime INT
910 )
911
912 -- Reverse Logistics stuff
913 CREATE TABLE #RLOrderParty
914 (
915 RLOrderParty_RecordID INT,
916 RLCarrierName VARCHAR(100),
917 RLOperatingCompany VARCHAR(100)
918 )
919
920 CREATE TABLE #RLSCAC
921 (
922 RLSCAC_RecordID INT,
923 RLSCAC CHAR(4)
924 )
925
926 --spitkyl: added customer pickup
927 CREATE TABLE #RLTicket
928 (
929 RLTicket_RecordID INT,
930 RLTicketNumber INT,
931 RLStatus VARCHAR(20),
932 RLSealSigned BIT,
933 RLSealNumber VARCHAR(50),
934 RLSealIntact BIT,
935 RLTotalBOLPieces INT,
936 RLTotalBOLPiecesSigned INT,
937 RLReturnMiles INT,
938 RLCustomerPickup BIT
939 )
940
941 --spitkyl: added status update date
942 CREATE TABLE #RLTicketDate
943 (
944 RLTicketDate_RecordID INT,
945 RLTicketCreateDate INT,
946 RLTicketCreateTime INT,
947 RLTicketInitialShipDate INT,
948 RLTicketInitialDeliveryDate INT,
949 RLTicketStatusUpdateDate INT,
950 RLTicketStatusUpdateTime INT
951 )
952
953 CREATE TABLE #RLLocation
954 (
955 RLLocation_RecordID INT,
956
957 RLHeadHaulOrigName NVARCHAR(200),
958 RLHeadHaulOrigAddress NVARCHAR(100),
959 RLHeadHaulOrigCity NVARCHAR(100),
960 RLHeadHaulOrigState NVARCHAR(100),
961 RLHeadHaulOrigZip NVARCHAR(20),
962 RLHeadHaulOrigOE VARCHAR(80),
963
964 RLHeadHaulDestName NVARCHAR(200),
965 RLHeadHaulDestAddress NVARCHAR(100),
966 RLHeadHaulDestCity NVARCHAR(100),
967 RLHeadHaulDestState NVARCHAR(100),
968 RLHeadHaulDestZip NVARCHAR(20),
969 RLHeadHaulDestOE VARCHAR(80),
970
971 RLReturnOrigName NVARCHAR(200),
972 RLReturnOrigAddress NVARCHAR(100),
973 RLReturnOrigCity NVARCHAR(100),
974 RLReturnOrigState NVARCHAR(100),
975 RLReturnOrigZip NVARCHAR(20),
976 RLReturnOrigOE VARCHAR(80),
977
978 RLReturnDestName NVARCHAR(200),
979 RLReturnDestAddress NVARCHAR(100),
980 RLReturnDestCity NVARCHAR(100),
981 RLReturnDestState NVARCHAR(100),
982 RLReturnDestZip NVARCHAR(20),
983 RLReturnDestOE VARCHAR(80)
984 )
985
986 CREATE TABLE #RLReference
987 (
988 RLReference_RecordID INT,
989 RLProNumber NVARCHAR(255),
990 RLSBOLNum NVARCHAR(255),
991 RLCustomerPO NVARCHAR(255),
992 RLCustomerOrderNum NVARCHAR(255),
993 RLRANum NVARCHAR(255),
994 RLCustRefNum NVARCHAR(255),
995
996 RLPickupNumber NVARCHAR(255)
997 )
998
999 CREATE TABLE #RLItem
1000 (
1001 RLItem_RecordID INT,
1002 RLProductName VARCHAR(200),
1003 RLItemValue DECIMAL(19,2),
1004 RLItemQuantity DECIMAL(19,2),
1005 RLItemWeight DECIMAL(19,2),
1006 RLSKU VARCHAR(50),
1007
1008 RLDamaged BIT,
1009 RLAccepted BIT,
1010 RLSalvageable BIT,
1011 RLDisposition VARCHAR(25),
1012 RLReason VARCHAR(50),
1013 RLEventType CHAR(50),
1014 RLErrorCode VARCHAR(25),
1015 RLProductOperatingCompany VARCHAR(10),
1016
1017 RLShortCode NVARCHAR(255),
1018
1019 RLComments VARCHAR(MAX),
1020
1021 COItemID INT
1022 )
1023
1024 CREATE TABLE #RLSummaryItem
1025 (
1026 RLSummaryItem_RecordID INT,
1027 RLSummaryValue DECIMAL(19,2),
1028 RLSummaryQuantity DECIMAL(19,2)
1029 )
1030
1031 CREATE TABLE #DropTrailer
1032 (
1033 DropTrailer_RecordID INT,
1034 DropTrailerShipper BIT,
1035 DropTrailerConsignee BIT,
1036 DropTrailerNotifiedByShipper VARCHAR(200),
1037 DropTrailerNotifiedByConsignee VARCHAR(200),
1038 ReceivedBy VARCHAR(200),
1039 PiecesDelivered VARCHAR(200),
1040 DeleteFlg BIT
1041 )
1042
1043 CREATE TABLE #INCOTerm
1044 (
1045 INCOTerm_RecordID INT,
1046 INCOTerm VARCHAR(10),
1047 INCOTermLocation VARCHAR(50)
1048 )
1049
1050 CREATE TABLE #ReasonCodes
1051 (
1052 ReasonCodes_RecordID INT,
1053 PLATEReason VARCHAR(255),
1054 DLATEReason VARCHAR(255)
1055 )
1056
1057 CREATE TABLE #Epayments
1058 (
1059 EPayments_RecordID INT,
1060 EPayApprovedBy VARCHAR(100),
1061 EPayPaidBy VARCHAR(100),
1062 EPayComments VARCHAR(250)
1063 )
1064
1065 CREATE TABLE #Load (
1066 Load_RecordID INT,
1067 LoadNumber INT,
1068 LoadHotY BIT, -- Either 1 ('Yes') or NULL (''), per requirements ,
1069 CustomEquipmentTypeID INT,
1070 CustomEquipmentType VARCHAR(100)
1071 )
1072
1073 --0 - Common,
1074 --2 - Payer
1075 --4 - Shipment(SubOrder)
1076 --8 - Origin
1077 --16 - Destination
1078 --32 - Item
1079
1080 CREATE TABLE #SummaryCore
1081 (
1082 RecordID int,
1083 OriginStopNumber int,
1084 DestStopNumber int,
1085 ShipmentType varchar(20)
1086 )
1087
1088 CREATE TABLE #Column
1089 (
1090 CName VARCHAR(50)
1091 )
1092
1093 CREATE TABLE #POCustomer
1094 (
1095 POCustomer_RecordID INT
1096 ,PartyNumber INT
1097 ,POCustomerName VARCHAR(200)
1098 ,CustomerAddress1 VARCHAR(100)
1099 ,CustomerAddress2 VARCHAR(100)
1100 ,CustomerCity VARCHAR(50)
1101 ,CustomerState VARCHAR(50)
1102 ,CustomerPostalCode VARCHAR(50)
1103 ,CustomerAccountCode VARCHAR(50)
1104 )
1105 CREATE TABLE #POBuyer
1106 (
1107 POBuyer_RecordID INT
1108 ,PartyNumber INT
1109 ,BuyerName VARCHAR(200)
1110 ,BuyerAddress1 VARCHAR(100)
1111 ,BuyerAddress2 VARCHAR(100)
1112 ,BuyerCity VARCHAR(50)
1113 ,BuyerState VARCHAR(50)
1114 ,BuyerPostalCode VARCHAR(50)
1115 ,BuyerAccountCode VARCHAR(50)
1116 )
1117 CREATE TABLE #POEndCustomer
1118 (
1119 EndCustomer_RecordID INT
1120 ,PartyNumber INT
1121 ,EndCustomerName VARCHAR(200)
1122 ,EndCustomerAddress1 VARCHAR(100)
1123 ,EndCustomerAddress2 VARCHAR(100)
1124 ,EndCustomerCity VARCHAR(50)
1125 ,EndCustomerState VARCHAR(50)
1126 ,EndCustomerPostalCode VARCHAR(50)
1127 ,EndCustomerAccountCode VARCHAR(50)
1128 )
1129 CREATE TABLE #POImporterofRecord
1130 (
1131 ImporterofRecord_RecordID INT
1132 ,PartyNumber INT
1133 ,ImporterofRecordName VARCHAR(200)
1134 ,ImporterofRecordAddress1 VARCHAR(100)
1135 ,ImporterofRecordAddress2 VARCHAR(100)
1136 ,ImporterofRecordCity VARCHAR(50)
1137 ,ImporterofRecordState VARCHAR(50)
1138 ,ImporterofRecordPostalCode VARCHAR(50)
1139 ,ImporterofRecordAccountCode VARCHAR(50)
1140 )
1141
1142 CREATE TABLE #POVendor
1143 (
1144 POVendor_RecordID INT
1145 ,PartyNumber INT
1146 ,POVendorName VARCHAR(200)
1147 ,VendorAddress1 VARCHAR(100)
1148 ,VendorAddress2 VARCHAR(100)
1149 ,VendorCity VARCHAR(50)
1150 ,VendorState VARCHAR(50)
1151 ,VendorPostalCode VARCHAR(50)
1152 ,VendorAccountCode VARCHAR(50)
1153 )
1154 CREATE TABLE #POManufacturer
1155 (
1156 Manufacturer_RecordID INT
1157 ,PartyNumber INT
1158 ,ManufacturerName VARCHAR(200)
1159 ,ManufacturerAddress1 VARCHAR(100)
1160 ,ManufacturerAddress2 VARCHAR(100)
1161 ,ManufacturerCity VARCHAR(50)
1162 ,ManufacturerState VARCHAR(50)
1163 ,ManufacturerPostalCode VARCHAR(50)
1164 ,ManufacturerAccountCode VARCHAR(50)
1165 )
1166 CREATE TABLE #POSeller
1167 (
1168 Seller_RecordID INT
1169 ,PartyNumber INT
1170 ,SellerName VARCHAR(200)
1171 ,SellerAddress1 VARCHAR(100)
1172 ,SellerAddress2 VARCHAR(100)
1173 ,SellerCity VARCHAR(50)
1174 ,SellerState VARCHAR(50)
1175 ,SellerPostalCode VARCHAR(50)
1176 ,SellerAccountCode VARCHAR(50)
1177 )
1178 CREATE TABLE #POItemLocation
1179 (
1180 POItemLocation_RecordID INT
1181 ,OriginLocationName VARCHAR(200)
1182 ,OriginLocationCity VARCHAR(100)
1183 ,OriginLocationState VARCHAR(100)
1184 ,OriginLocationCountry VARCHAR(50)
1185
1186 ,DestinationLocationName VARCHAR(200)
1187 ,DestinationLocationCity VARCHAR(100)
1188 ,DestinationLocationState VARCHAR(100)
1189 ,DestinationLocationCountry VARCHAR(50)
1190 )
1191
1192 CREATE TABLE #POItems
1193 (
1194 POItems_RecordID INT
1195 ,InnerPackOriginalQuantity INT
1196 ,InnerPackQuantity INT
1197 ,InnerPackWeight DECIMAL(19,2)
1198 ,InnerPackType VARCHAR(50)
1199 ,InnerPackLength DECIMAL(19,2)
1200 ,InnerPackWidth DECIMAL(19,2)
1201 ,InnerPackHeight DECIMAL(19,2)
1202 ,InnerPackVolume DECIMAL(19,2)
1203 ,OuterPackStuffingQuantity INT
1204 ,OuterPackType VARCHAR(50)
1205 ,OuterPackLength DECIMAL(19,2)
1206 ,OuterPackWidth DECIMAL(19,2)
1207 ,OuterPackHeight DECIMAL(19,2)
1208 ,OuterPackVolume DECIMAL(19,2)
1209 ,OuterPackWeight DECIMAL(19,2)
1210 ,OuterPackQuantity INT
1211 ,POSKU VARCHAR(50)
1212 ,POProductCode VARCHAR(50)
1213 ,POHTCode VARCHAR(50)
1214 ,ItemName VARCHAR(100)
1215 ,TotalValue DECIMAL(19,2)
1216 ,POMode VARCHAR(50)
1217 ,POItemStatus VARCHAR(50)
1218 ,POINCOTerm VARCHAR(100)
1219 ,INCOLocation VARCHAR(100)
1220 ,POStatus VARCHAR(50)
1221 ,COItemID INT
1222 ,POItemID INT
1223 ,PlannedQuantity INT
1224 ,InTransitQuantity INT
1225 ,DeliveredQuantity INT
1226 )
1227
1228 CREATE TABLE #POItemReference
1229 (
1230 POItemReference_RecordID INT
1231 ,POLineNumber VARCHAR(50)
1232 ,VendorPONumber VARCHAR(50)
1233 ,VendorLineNumber VARCHAR(50)
1234 ,CustomerPONumber VARCHAR(50)
1235 ,BuyerID VARCHAR(50)
1236 )
1237 CREATE TABLE #POItemDate
1238 (
1239 POItemDate_RecordID INT
1240 ,RequestedBookingStartDate INT
1241 ,RequestedBookingDate INT
1242 ,ShipStartDate INT
1243 ,ShipEndDate INT
1244 ,RequestedPickupStartDate INT
1245 ,RequestedPickupDate INT
1246 ,RequestedDeliveryStartDate INT
1247 ,RequestedDeliveryDate INT
1248
1249 )
1250 CREATE TABLE #COrderDate
1251 (
1252 COrderDate_RecordID INT
1253 ,RecBookingDate INT
1254 )
1255 CREATE TABLE #CargoWiseCustoms
1256 (
1257 CargoWise_RecordID INT
1258 ,AgricultureHoldDate DATETIME
1259 ,OGAFDAExamDate DATETIME
1260 )
1261/*<><><><><><><>Jeremy Dixon change 12/11/2013<><><><><><><>*/
1262CREATE TABLE #SPODLocationDates_capture
1263 (
1264 SPODLocationID INT,
1265 KeyLocationID INT,
1266 DateType VARCHAR(50),
1267 DateValue INT,
1268 TimeValue INT
1269 )
1270/*<><><><><><><>Jeremy Dixon change 12/11/2013<><><><><><><>*/
1271CREATE TABLE #SPODates_capture
1272 (
1273 SPOrderID INT,
1274 DateType VARCHAR(50),
1275 DateValue INT,
1276 TimeValue INT
1277 )
1278
1279/*<><><><><><><>Jeremy Dixon change 12/11/2013<><><><><><><>*/
1280 CREATE TABLE #LASTIMDEventStage
1281 (RecordID INT
1282 ,Note NVARCHAR(255)
1283 ,City VARCHAR(100)
1284 ,[State] VARCHAR(2)
1285 ,SPOrderID INT
1286 ,EventDate smalldatetime)
1287
1288/*<><><><><><><>Jeremy Dixon change 12/11/2013<><><><><><><>*/
1289CREATE TABLE #WantedBookTypes
1290 (BookType VARCHAR(3))
1291
1292/*NEW OR CHANGED Jeremy Dixon 1/2014*/
1293 CREATE TABLE #CaptureLoadOrder
1294 ([Status] CHAR (5)
1295 ,LoadNumber INT
1296 ,Mode VARCHAR(50))
1297
1298
1299/*NEW OR CHANGED Jeremy Dixon 1/2014*/
1300 CREATE TABLE #Conveyance
1301 (SPOrder_RecordID INT
1302 ,Conveyance VARCHAR(500))
1303
1304
1305CREATE TABLE #OrderedSpace
1306(OrderedSpace_RecordID INT,
1307 OrderedSpace INT)
1308
1309CREATE CLUSTERED INDEX IDX_C_Conveyance ON #Conveyance (SPOrder_RecordID)
1310/*NEW OR CHANGED Jeremy Dixon 1/2014*/
1311 CREATE TABLE #ContractNum
1312 (SPOrder_RecordID INT
1313 ,ContractNum VARCHAR(500))
1314
1315CREATE CLUSTERED INDEX IDX_C_ContractNum ON #ContractNum (SPOrder_RecordID)
1316/*NEW OR CHANGED Jeremy Dixon 1/2014*/
1317 CREATE TABLE #CarrierName
1318 (SPOrder_RecordID INT
1319 ,CarrierName VARCHAR(500))
1320
1321CREATE CLUSTERED INDEX IDX_C_CarrierName ON #CarrierName (SPOrder_RecordID)
1322/*NEW OR CHANGED Jeremy Dixon 1/2014*/
1323 CREATE TABLE #BookingNum
1324 (SPOrder_RecordID INT
1325 ,BookingNum VARCHAR(500))
1326
1327CREATE CLUSTERED INDEX IDX_C_BookingNum ON #BookingNum (SPOrder_RecordID)
1328/*NEW OR CHANGED Jeremy Dixon 1/2014*/
1329 CREATE TABLE #EquipmentType
1330 (SPOrder_RecordID INT
1331 ,EquipmentType VARCHAR(500))
1332
1333CREATE CLUSTERED INDEX IDX_C_EquipmentType ON #EquipmentType (SPOrder_RecordID)
1334/*NEW OR CHANGED Jeremy Dixon 1/2014*/
1335 CREATE TABLE #TractorNum
1336 (SPOrder_RecordID INT
1337 ,TractorNum VARCHAR(500))
1338
1339CREATE CLUSTERED INDEX IDX_C_TractorNum ON #TractorNum (SPOrder_RecordID)
1340/*NEW OR CHANGED Jeremy Dixon 1/2014*/
1341 CREATE TABLE #TrailerNum
1342 (SPOrder_RecordID INT
1343 ,TrailerNum VARCHAR(500))
1344
1345CREATE CLUSTERED INDEX IDX_C_TrailerNum ON #TrailerNum (SPOrder_RecordID)
1346/*NEW OR CHANGED Jeremy Dixon 1/2014*/
1347 CREATE TABLE #TrailerSize
1348 (SPOrder_RecordID INT
1349 ,TrailerSize VARCHAR(500))
1350
1351CREATE CLUSTERED INDEX IDX_C_TrailerSize ON #TrailerSize (SPOrder_RecordID)
1352/*NEW OR CHANGED Jeremy Dixon 1/2014*/
1353 CREATE TABLE #AirLineCarrier
1354 (SPOrder_RecordID INT
1355 ,AirLineCarrier VARCHAR(500))
1356
1357CREATE CLUSTERED INDEX IDX_C_AirLineCarrier ON #AirLineCarrier (SPOrder_RecordID)
1358/*NEW OR CHANGED Jeremy Dixon 1/2014*/
1359 CREATE TABLE #FlightNumber
1360 (SPOrder_RecordID INT
1361 ,FlightNumber VARCHAR(500))
1362
1363CREATE CLUSTERED INDEX IDX_C_FlightNumber ON #FlightNumber (SPOrder_RecordID)
1364
1365/*NEW OR CHANGED Jeremy Dixon 1/2014*/
1366 CREATE INDEX IDX_Ref_runKey ON #REF (ReferenceType, Ref_RecordID) INCLUDE(ReferenceNumber)
1367 CREATE INDEX IDX_Row_runKey ON #Row (ServiceLevel, RecordID)
1368 CREATE INDEX IDX_Row_runKey2 ON #Row (COSDetailID) INCLUDE(RecordID)
1369 CREATE CLUSTERED INDEX IDX_C_ITEM ON #Item (Item_RecordID)
1370
1371 -- ========================================================================================
1372 -- LOAD #ROW AND #COLUMN TABLES
1373 -- ========================================================================================
1374
1375 --PRINT 'Load #Row and #Column Tables'
1376
1377 DECLARE
1378 @UserID INT
1379 ,@SVID INT
1380 ,@StatusMappingID INT
1381 --,@LogID INT
1382 ,@SelectClause VARCHAR(MAX)
1383 ,@SummarizeShipment BIT
1384 ,@SummarizeOcean BIT
1385 ,@ReportLevel INT
1386 ,@RoutingFeature INT
1387 ,@sql NVARCHAR(MAX)
1388 ,@sqlDistinct NVARCHAR(10)
1389 ,@collist NVARCHAR(MAX)
1390 ,@collist2 NVARCHAR(MAX)
1391 ,@HideMode BIT
1392 ,@HideExpressComments BIT
1393 ,@SpoofBookedStatus BIT
1394 ,@DateType VARCHAR(50)
1395 ,@StartDate SMALLDATETIME
1396 ,@EndDate SMALLDATETIME
1397 ,@InvoiceNumber varchar(100)
1398 ,@ListBillNumber varchar(100)
1399
1400 /********************************************************************************************************/
1401 /******************** LOAD VARIABLES WITH REPORT CRITERIA************************************************/
1402 /********************************************************************************************************/
1403 --PRINT 'Load Variables with report criteria'
1404
1405 SELECT @UserID = A.UserID
1406 ,@SVID = A.SessionViewID
1407 ,@SelectClause = A.SelectClause
1408 ,@DateType = A.DateType
1409 ,@StartDate = A.StartDate
1410 ,@EndDate = A.EndDate
1411 ,@InvoiceNumber = A.InvoiceNums
1412 ,@ListBillNumber = A.ListBillNums
1413-- ,@SummarizeShipment = A.SummarizeShipment
1414-- ,@SummarizeOcean = A.SummarizeOcean
1415 ,@ReportLevel = A.ReportLevel
1416 ,@SpoofBookedStatus = COALESCE(A.SpoofBookedStatus, 0)
1417 FROM CHRWOnline.dbo.AdHocReport AS A WITH(NOLOCK)
1418 WHERE A.LogID = @LogID
1419
1420 -- shipment summary = 1
1421 -- put levels from flags enum in table?
1422 IF @ReportLevel & 1 = 1
1423 BEGIN
1424 SET @SummarizeShipment = 1
1425 END
1426 ELSE
1427 BEGIN
1428 SET @SummarizeShipment = 0
1429 END
1430
1431 -- ocean summary = 4
1432 IF @ReportLevel & 4 = 4
1433 BEGIN
1434 SET @SummarizeOcean = 1
1435 END
1436 ELSE
1437 BEGIN
1438 SET @SummarizeOcean = 0
1439 END
1440
1441 SELECT @StatusMappingID = SM.StatusMappingID
1442 FROM CHRWOnline.dbo.UT_User AS U WITH (NOLOCK)
1443 INNER JOIN CHRWOnline.dbo.UT_StatusMapping AS SM WITH (NOLOCK)
1444 ON U.StatusMappingCode = SM.StatusMappingCode
1445 WHERE U.UserID = @UserID
1446
1447 IF EXISTS
1448 (
1449 SELECT 1
1450 FROM CHRWOnline.dbo.UT_AssignedFeature AS AF WITH(NOLOCK)
1451 INNER JOIN CHRWOnline.dbo.UT_Feature AS F WITH(NOLOCK)
1452 ON AF.FeatureID = F.FeatureID
1453 WHERE
1454 AF.AssignedToID = @UserID
1455 AND F.FeatureName = 'Routing Link Display')
1456 BEGIN
1457SET @RoutingFeature = 1
1458 END
1459
1460 IF EXISTS
1461 (
1462 SELECT 1
1463 FROM CHRWOnline.dbo.UT_AssignedFeature AS AF WITH(NOLOCK)
1464 INNER JOIN CHRWOnline.dbo.UT_Feature AS F WITH(NOLOCK)
1465 ON AF.FeatureID = F.FeatureID
1466 WHERE
1467 AF.AssignedToID = @UserID
1468 AND F.FeatureName = 'ServiceLevelShipment'
1469 )
1470 BEGIN
1471 SET @HideMode = 1
1472 END
1473 ELSE
1474 BEGIN
1475 SET @HideMode = 0
1476 END
1477
1478 IF EXISTS
1479 (
1480 SELECT 1
1481 FROM CHRWOnline.dbo.UT_AssignedFeature AS AF WITH(NOLOCK)
1482 INNER JOIN CHRWOnline.dbo.UT_Feature AS F WITH(NOLOCK)
1483 ON AF.FeatureID = F.FeatureID
1484 WHERE
1485 AF.AssignedToID = @UserID
1486 AND F.FeatureName = 'Show Express Comments'
1487 )
1488
1489 BEGIN
1490 SET @HideExpressComments = 0
1491 END
1492 ELSE
1493 BEGIN
1494 SET @HideExpressComments = 1
1495 END
1496
1497 -- ========================================================================================================
1498 -- Build #SummaryCore Table
1499 -- ========================================================================================================
1500 IF @SummarizeShipment = 1
1501 BEGIN
1502 INSERT INTO #SummaryCore
1503 (
1504 RecordID,
1505 OriginStopNumber,
1506 DestStopNumber,
1507 ShipmentType
1508 )
1509 SELECT
1510 R.RecordID,
1511 MIN(R.OriginStopNumber),
1512 MAX(R.DestStopNumber),
1513 'Summary Load'
1514 FROM #Row AS R
1515 WHERE R.ShipmentType = 'Multi OD Load'
1516 GROUP BY R.RecordID
1517 UNION ALL
1518 SELECT
1519 R.RecordID,
1520 MIN(R.OriginStopNumber),
1521 MAX(R.DestStopNumber),
1522 'Summary Plan Load'
1523 FROM #Row AS R
1524 WHERE R.ShipmentType = 'Multi OD Plan Load'
1525 GROUP BY R.RecordID
1526 END
1527
1528 UPDATE #Row SET DisplayServiceFlg = 1 WHERE LevelNumber = 1
1529
1530 UPDATE R SET DisplayServiceFlg = 1
1531 FROM #Row AS R
1532 INNER JOIN dbo.COService AS CS WITH(NOLOCK)
1533 ON R.COServiceID = CS.COServiceID
1534 INNER JOIN dbo.COSGroup AS SG WITH(NOLOCK)
1535 ON CS.COSGroupID = SG.COSGroupID
1536 AND CS.FirstLoadNumber = SG.PrimaryLoadNumber
1537 WHERE R.LevelNumber = 2
1538
1539 UPDATE R SET DisplayServiceFlg = 1
1540 FROM #Row AS R WITH(NOLOCK)
1541 WHERE R.COServiceID IN
1542 (
1543 SELECT TOP 1 R2.COServiceID
1544 FROM #Row AS R2
1545 INNER JOIN dbo.COLocation AS CL WITH(NOLOCK)
1546 ON R2.COSDetailID = CL.COSDetailID
1547 INNER JOIN dbo.[Load] AS L WITH(NOLOCK)
1548 ON R2.LoadNumber = L.LoadNumber
1549 AND L.MaxStopNbr = CL.StopNumber
1550 AND R2.SourceTypeID = L.SourceTypeID
1551 AND L.InternationalFlg=0
1552 WHERE R.RecordID = R2.RecordID
1553 ) AND R.LevelNumber = 2
1554
1555 INSERT INTO #Column(CName)
1556 SELECT COL.VCHAR FROM dbo.VARCHAR_ListParser(@SelectClause + ',') AS COL
1557
1558 CREATE CLUSTERED INDEX INX_Column_CName ON #Column(CName)
1559
1560 -- =====================================================================================================================
1561 -- SELECT WHAT TABLES NEED TO GET POPULATED?
1562 -- =====================================================================================================================
1563 DECLARE
1564 @ProcessAlerts BIT,
1565 @ProcessPayers BIT,
1566 @ProcessSpecialInstructions BIT,
1567 @ProcessCustomerLocations BIT,
1568 @ProcessMisc BIT,
1569 @ProcessPOD BIT,
1570 @ProcessMiscDates BIT,
1571 @ProcessInterLocations BIT,
1572 @ProcessFUDates BIT,
1573 @ProcessLFUDates BIT,
1574 @ProcessInvoices BIT,
1575 @ProcessItems BIT,
1576 @ProcessFlatbed BIT,
1577 @ProcessItemSummaries BIT,
1578 @ProcessDriverTixSummaries BIT,
1579 @ProcessItemSummaryTexts BIT,
1580 @ProcessComments BIT,
1581 @ProcessCOServices BIT,
1582 @ProcessCHRStatuses BIT,
1583 @ProcessLastInvoices BIT,
1584 @ProcessLastEvents BIT,
1585 @ProcessLastIMDLEvents BIT,
1586 @ProcessSPOrders BIT,
1587 @ProcessSPOrderIntls BIT,
1588 @ProcessSPOrderOthers BIT,
1589 @ProcessSCACs BIT,
1590 @ProcessCustoms BIT,
1591 @ProcessPoolCrossLocations BIT,
1592 @ProcessPoolCrossLocationDates BIT,
1593 @ProcessMethodsOfPayment BIT,
1594 --Reverse logistics
1595 @ProcessRLOrderParty BIT,
1596 @ProcessRLSCAC BIT,
1597 @ProcessRLTicket BIT,
1598 @ProcessRLTicketDate BIT,
1599 @ProcessRLLocation BIT,
1600 @ProcessRLReference BIT,
1601 @ProcessRLItem BIT,
1602 @ProcessRLSummaryItem BIT,
1603 @ProcessDropTrailer BIT,
1604 @ProcessINCOTerm BIT,
1605 @ProcessReasonCodes BIT,
1606 @ProcessEPayments BIT,
1607 @ProcessCompliance BIT,
1608 @ProcessStopNums BIT,
1609 @ProcessLoad BIT,
1610 @ProcessPOCustomer BIT,
1611 @ProcessPOBuyer BIT,
1612 @ProcessPOEndCustomer BIT,
1613 @ProcessPOImporter BIT,
1614 @ProcessPOVendor BIT,
1615 @ProcessPOManufacturer BIT,
1616 @ProcessPOSeller BIT,
1617 @ProcessPOLocation BIT,
1618 @ProcessPOItems BIT,
1619 @ProcessPOItemReference BIT,
1620 @ProcessPOItemDate BIT,
1621 @ProcessCustomsCargoWise BIT,
1622 @ProcessCOrderDates BIT,
1623 @ProcessDisplayShipmentNumbers BIT,
1624 @ProcessOrderedSpace BIT
1625
1626 SELECT @ProcessAlerts = 1
1627 FROM #Column AS C
1628 WHERE C.CName='ShipmentAlerts.*'
1629
1630 SELECT @ProcessStopNums = 1
1631 FROM #Column AS C WITH (NOLOCK)
1632 WHERE C.CName = 'StopNums'
1633
1634 SELECT @ProcessPayers = 1
1635 FROM #Column AS C
1636 WHERE C.CName IN
1637 (
1638 'PayerName',
1639 'PayerAddress1',
1640 'PayerAddress2',
1641 'PayerCity',
1642 'PayerState',
1643 'PayerZip',
1644 'PayerLocationID'
1645 )
1646
1647 SELECT @ProcessMethodsOfPayment = 1
1648 FROM #Column AS C
1649 WHERE C.CName = 'MethodOfPayment'
1650
1651 SELECT @ProcessSpecialInstructions = 1
1652 FROM #Column AS C
1653 WHERE C.CName IN
1654 (
1655 'OrigSpecialInstructions',
1656 'DestSpecialinstructions'
1657 )
1658
1659 SELECT @ProcessCustomerLocations = 1
1660 FROM #Column AS C
1661 WHERE C.CName IN
1662 (
1663 'OrigName',
1664 'OrigAddress1',
1665 'OrigAddress2',
1666 'OrigCity',
1667 'OrigState',
1668 'OrigCountry',
1669 'OrigZip',
1670 'OrigLocationID',
1671 'OrigAirportCode',
1672 'DestName',
1673 'DestAddress1',
1674 'DestAddress2',
1675 'DestCity',
1676 'DestState',
1677 'DestCountry',
1678 'DestZip',
1679 'DestLocationID',
1680 'DestAirportCode'
1681 )
1682
1683 SELECT @ProcessMisc = 1
1684 FROM #Column AS C
1685 WHERE C.CName IN
1686 (
1687 'CustomerName',
1688 'ShipperName',
1689 'ConsigneeName',
1690 'VendorName',
1691 'ImporterOfRecord',
1692 'Buyer',
1693 'OrderedBy',
1694 'EnteredBy',
1695 'MasterLinehaulName'
1696 )
1697
1698 SELECT @ProcessMiscDates = 1
1699 FROM #Column AS C
1700 WHERE C.CName IN
1701 (
1702 'CloseDate',
1703 'DocumentTrackingDate',
1704 'DeliveryOrderCreatedDate',
1705 'TruckloadActivityDate',
1706 'EstimatedPickupDate',
1707 'EstimatedDeliveryDate'
1708 )
1709
1710 SELECT @ProcessInterLocations = 1
1711 FROM #Column AS C
1712 WHERE C.CName IN
1713 (
1714 'OrigTerminalName',
1715 'OrigTerminalCity',
1716 'OrigRampName',
1717 'OrigRampCity',
1718 'LoadingPort',
1719 'LoadingPortCountry',
1720 'DischargePort',
1721 'DischargePortCountry',
1722 'DestRampName',
1723 'DestRampCity',
1724 'DestTerminalName',
1725 'DestTerminalCity'
1726 )
1727
1728 SELECT @ProcessFUDates = 1
1729 FROM #Column AS C
1730 WHERE C.CName IN
1731 (
1732 'EnterDate',
1733 'EnterTime',
1734 'EarliestReqPickupDate',
1735 'EarliestReqPickupTime',
1736 'LatestReqPickupDate',
1737 'LatestReqPickupTime',
1738 'EarliestSchedPickupDate',
1739 'EarliestSchedPickupTime',
1740 'LatestSchedPickupDate',
1741 'LatestSchedPickupTime',
1742 'EarliestActualPickupDate',
1743 'EarliestActualPickupTime',
1744 'LatestActualPickupDate',
1745 'LatestActualPickupTime',
1746 'ShipperDropTrailerArrivalDate',
1747 'ShipperDropTrailerArrivalTime',
1748 'ShipperDropTrailerReadyDate',
1749 'ShipperDropTrailerReadyTime',
1750 'EarliestReqDeliveryDate',
1751'EarliestReqDeliveryTime',
1752 'LatestReqDeliveryDate',
1753 'LatestReqDeliveryTime',
1754 'EarliestSchedDeliveryDate',
1755 'EarliestSchedDeliveryTime',
1756 'LatestSchedDeliveryDate',
1757 'LatestSchedDeliveryTime',
1758 'EarliestActualDeliveryDate',
1759 'EarliestActualDeliveryTime',
1760 'LatestActualDeliveryDate',
1761 'LatestActualDeliveryTime',
1762 'ConsigneeDropTrailerArrivalDate',
1763 'ConsigneeDropTrailerArrivalTime',
1764 'ConsigneeDropTrailerReadyDate',
1765 'ConsigneeDropTrailerReadyTime'
1766 )
1767
1768 SELECT @ProcessLFUDates = 1
1769 FROM #Column AS C
1770 WHERE C.CName IN
1771 (
1772'OrigTerminalETADate',
1773 'OrigTerminalArrivalDate',
1774 'OrigTerminalArrivalTime',
1775 'OrigTerminalDepartDate',
1776 'OrigTerminalDepartTime',
1777 'OrigRampCutOffDate',
1778 'OrigRampCutOffTime',
1779 'OrigRampArrivalDate',
1780 'OrigRampArrivalTime',
1781 'OrigRampRampedDate',
1782 'OrigRampRampedTime',
1783 'PortCutoffDate',
1784 'OriginalPortETDDate',
1785 'PortETDDate',
1786 'OriginalPortETADate',
1787 'PortETADate',
1788 'ActualPortArrivalDate',
1789 'ActualPortDepartDate',
1790 'DestRampArrivalDate',
1791 'DestRampArrivalTime',
1792 'DestRampDeRampedDate',
1793 'DestRampDeRampedTime',
1794 'RailETADate',
1795 'DestTerminalETADate',
1796 'DestTerminalArrivalDate',
1797 'DestTerminalArrivalTime',
1798 'DestTerminalDepartDate',
1799 'DestTerminalDepartTime',
1800 'IMDLPromiseDate',
1801 'DestRampETADate',
1802 'EmptyReturnDate',
1803 'LastFreeDate'
1804 )
1805
1806 SELECT @ProcessInvoices = 1
1807 FROM #Column AS C
1808 WHERE C.CName IN
1809 (
1810 'InvoiceDate',
1811 'InvoiceNum',
1812 'CHRListBillNum',
1813 'InvoiceBalance',
1814 'InvoiceStatus',
1815 'InvoiceReleaseDate',
1816 'ReceivedAmount',
1817 'InvoiceTotal'
1818 )
1819
1820 -- Need to populate items only if we aren't doing summary
1821 --TODO Check for report level set.
1822 IF @SummarizeShipment = 0 AND @SummarizeOcean = 0
1823 BEGIN
1824 SELECT @ProcessItems = 1
1825 FROM #Column AS C
1826 WHERE C.CName IN
1827 (
1828 'ItemID',
1829 'ExFactoryDate',
1830 'ActualQuantity',
1831 'HazardousItem',
1832 'Class',
1833 'Value',
1834 'ExpectedQuantity',
1835 'Weight',
1836 'TempSensitive',
1837 'SKU',
1838 'CustCommodityCode',
1839 'HTCode',
1840 'Pallets',
1841 'UnitOfMeasure',
1842 'CustCommodityName',
1843 'DimensionalWeight',
1844 'PalletSpaces',
1845 'ItemDescription',
1846 'ActualEDIPackagingCode',
1847 'ActualVolume',
1848 'Hot',
1849 'InnerPack',
1850 'UnitsPetPallet',
1851 'MasterPack',
1852
1853 'UPC',-- 05/02/2008 GANASAD Need to populate Items if we have to populate ItemRefs.
1854 'NMFC',
1855 'CustSpecific1',
1856 'CustSpecific2',
1857 'ProductCode',
1858 'PLU',
1859 'EAN',
1860 'HTCode',
1861 'VendorPO',
1862 'JobNum',
1863 'PONum',
1864 'LotNumber',
1865 'ItemRefNums',
1866 'ItemLength',
1867 'ItemWidth',
1868 'ItemHeight',
1869 'OriginalQuantity',
1870 'OriginalWeight',
1871 'OriginalVolume',
1872 'OriginalNMFC',
1873 'OriginalPallets',
1874 'OriginalFreightClass',
1875 'OriginalPalletSpaces',
1876 'ExpectedMinWeight',
1877 'ExpectedMaxWeight'
1878 )
1879
1880 SELECT @ProcessFlatbed = 1, @ProcessItems = 1
1881 FROM #Column AS C
1882 WHERE C.CName IN
1883 (
1884 'Overdimensional',
1885 'EquipmentTypeCode',
1886 'TarpLength',
1887 'RequiredChains',
1888 'RequiredStraps',
1889 'CoilRacks',
1890 'LoadingType'
1891 )
1892 END
1893
1894 SELECT @ProcessItemSummaries = 1
1895 FROM #Column AS C
1896 WHERE C.CName IN
1897 (
1898 'SummaryActualQuantity',
1899 'SummaryExpectedQuantity',
1900 'SummaryActualPallets',
1901 'SummaryExpectedPallets',
1902 'SummaryActualWeight',
1903'SummaryExpectedMinWeight',
1904 'SummaryHazardous',
1905 'SummaryPalletSpaces',
1906 'SummaryExpectedMaxWeight',
1907 'SummaryVolume',
1908 'SummaryDimensionalWeight',
1909 'SummaryChargeableWeight',
1910 'SummaryUnitOfMeasure',
1911 'SummaryHot',
1912 'SummaryInnerPack',
1913 'SummaryOverdimensional',
1914 'SummaryOriginalQuantity',
1915 'SummaryOriginalWeight',
1916 'SummaryOriginalVolume',
1917 'SummaryOriginalPallets',
1918 'SummaryOriginalPalletSpaces'
1919 )
1920
1921 SELECT @ProcessDriverTixSummaries = 1
1922 FROM #Column AS C
1923 WHERE C.CName IN
1924 (
1925 'SummaryDriverHeavyWeightTix',
1926 'SummaryDriverLightWeightTix'
1927 )
1928
1929 SELECT @ProcessItemSummaryTexts = 1
1930 FROM #Column AS C
1931 WHERE C.CName IN
1932 (
1933 'SummaryCommodity',
1934 'SummaryDescription'
1935 )
1936
1937 -- #Refs and #ItemRefs will do the WHERE EXISTS because they check individually
1938 -- (ie, for ConfirmationNumber, CustRefNum, and so on) as well as for buckets.
1939 -- We'd end up having to create twenty different variables.
1940 --
1941 -- Same thing for all the charges -- #AccessorialCharge and so on.
1942
1943 SELECT @ProcessComments = 1
1944 FROM #Column AS C
1945 WHERE C.CName='Comment'
1946
1947 SELECT @ProcessCOServices = 1
1948 FROM #Column AS C
1949 WHERE C.CName IN
1950 (
1951 'Mode',
1952 'Expedited',
1953 'ExpeditedReason',
1954 'InboundStatus',
1955 'FinancialCondition',
1956 'BaselineCharge',
1957 'NonConsolidationCharge',
1958 'CHRStatus',
1959 'RoutedShipments',
1960 'ServiceLevel',
1961 'OrderMode',
1962 'LoadMode'
1963 )
1964
1965 SELECT @ProcessCompliance = 1
1966 FROM #Column AS C
1967WHERE C.CName IN
1968 (
1969 'NonComplianceCode',
1970 'NonComplianceCodeReason'
1971)
1972
1973 SELECT @ProcessLastInvoices = 1
1974 FROM #Column AS C
1975 WHERE C.CName IN
1976(
1977 'Invoiced',
1978 'LastInvoiceDate'
1979 )
1980
1981 SELECT @ProcessLastEvents = 1
1982 FROM #Column AS C
1983 WHERE C.CName='LastEvent'
1984
1985 SELECT @ProcessLastIMDLEvents = 1
1986 FROM #Column AS C
1987 WHERE C.CName = 'LastIMDLEvent'
1988
1989 SELECT @ProcessSPOrders = 1
1990 FROM #Column AS C
1991 WHERE C.CName IN
1992 (
1993 'Conveyance',
1994 'ContractNum',
1995 'BookingNum',
1996 'CarrierName',
1997 'LTLSCAC',
1998 'EquipmentType',
1999 'TractorNum',
2000 'TrailerNum',
2001 'DeliveryCarrierName',
2002 'TenderedToCarrierName',
2003 'TrailerSize',
2004 'BookingDate',
2005 'AirLineCarrier',
2006 'FlightNumber'
2007 )
2008
2009 SELECT @ProcessSPOrderIntls = 1
2010 FROM #Column AS C
2011 WHERE C.CName IN
2012 (
2013 'ContainerNumber',
2014 'ContainerType'
2015 )
2016
2017 SELECT @ProcessSPOrderOthers = 1
2018 FROM #Column AS C
2019 WHERE C.CName IN
2020 (
2021 'DeliveryCarrierName',
2022 'TenderedToCarrierName'
2023 )
2024
2025 SELECT @ProcessSCACs = 1
2026 FROM #Column AS C
2027 WHERE C.CName IN
2028 (
2029 'LTLSCAC'
2030 )
2031
2032 SELECT @ProcessCustoms = 1
2033 FROM #Column AS C
2034 WHERE C.CName IN
2035 (
2036 'ITNumber',
2037 'SSLReleaseDate',
2038 'EntryLocation',
2039 'OGAReleaseDate',
2040 'ReceiptDocsDate',
2041 'ITLocation',
2042 'EntryDate',
2043 'ExamRequiredDate',
2044 'TenderedToCarrierDate',
2045 'FDAEntryDate',
2046 'ITDate',
2047 'EntryNum',
2048 'CustomsHoldDate',
2049 'TurnedOverDate',
2050 'FDAReqDate',
2051 'ReleaseDate',
2052 'BrokerName',
2053 'OGAHoldDate',
2054 'Notes',
2055 'FDASubmitDate',
2056 'ISFID',
2057 'ISFDate',
2058 'DeclaredValue'
2059 )
2060
2061SELECT @ProcessPoolCrossLocations = 1
2062 FROM #Column AS C
2063 WHERE C.CName IN
2064 (
2065 'PoolpointName',
2066 'PoolpointCity',
2067 'PoolpointState',
2068'CrossDockName',
2069 'CrossDockCity',
2070 'CrossDockState'
2071 )
2072
2073 SELECT @ProcessPoolCrossLocationDates = 1
2074 FROM #Column AS C
2075 WHERE C.CName IN
2076 (
2077 'PoolpointSchedArrivalDate',
2078 'PoolpointSchedArrivalTime',
2079 'PoolpointSchedDepartureDate',
2080 'PoolpointSchedDepartureTime',
2081 'PoolpointActualArrivalDate',
2082 'PoolpointActualArrivalTime',
2083 'PoolpointActualDepartureDate',
2084 'PoolpointActualDepartureTime',
2085 'CrossDockArrivalDate',
2086 'CrossDockArrivalTime',
2087 'CrossDockSchedDepartureDate',
2088 'CrossDockSchedDepartureTime',
2089 'CrossDockActualDepartureDate',
2090 'CrossDockActualDepartureTime'
2091 )
2092
2093 -- reverse logistics:
2094 SELECT @ProcessRLOrderParty = 1
2095FROM #Column AS C
2096 WHERE C.CName IN
2097 (
2098 'RLCarrierName',
2099 'RLOperatingCompany'
2100 )
2101
2102 SELECT @ProcessRLSCAC = 1
2103 FROM #Column AS C
2104 WHERE C.CName IN
2105 (
2106 'RLSCAC'
2107 )
2108
2109 SELECT @ProcessRLTicket = 1
2110 FROM #Column AS C
2111 WHERE C.CName IN
2112 (
2113 'RLTicketNumber',
2114 'RLStatus',
2115 'RLSealSigned',
2116 'RLSealNumber',
2117 'RLSealIntact',
2118 'RLTotalBOLPieces',
2119 'RLTotalBOLPiecesSigned',
2120 'RLReturnMiles',
2121 'RLCustomerPickup'
2122 )
2123
2124 SELECT @ProcessRLTicketDate = 1
2125 FROM #Column AS C
2126 WHERE C.CName IN
2127 (
2128 'RLTicketCreateDate',
2129 'RLTicketCreateTime',
2130 'RLTicketInitialShipDate',
2131 'RLTicketInitialDeliveryDate',
2132 'RLTicketStatusUpdateDate',
2133 'RLTicketStatusUpdateTime'
2134 )
2135
2136 SELECT @ProcessRLLocation = 1
2137 FROM #Column AS C
2138 WHERE C.CName IN
2139 (
2140 'RLHeadHaulOrigName',
2141 'RLHeadHaulOrigAddress',
2142 'RLHeadHaulOrigCity',
2143 'RLHeadHaulOrigState',
2144 'RLHeadHaulOrigZip',
2145 'RLHeadHaulOrigOE',
2146
2147 'RLHeadHaulDestName',
2148 'RLHeadHaulDestAddress',
2149 'RLHeadHaulDestCity',
2150 'RLHeadHaulDestState',
2151 'RLHeadHaulDestZip',
2152 'RLHeadHaulDestOE',
2153
2154 'RLReturnOrigName',
2155 'RLReturnOrigAddress',
2156 'RLReturnOrigCity',
2157 'RLReturnOrigState',
2158 'RLReturnOrigZip',
2159 'RLReturnOrigOE',
2160
2161 'RLReturnDestName',
2162 'RLReturnDestAddress',
2163 'RLReturnDestCity',
2164 'RLReturnDestState',
2165 'RLReturnDestZip',
2166 'RLReturnDestOE'
2167 )
2168
2169 SELECT @ProcessRLReference = 1
2170 FROM #Column AS C
2171 WHERE C.CName IN
2172 (
2173 'RLProNumber',
2174 'RLSBOLNum',
2175 'RLCustomerPO',
2176 'RLCustomerOrderNum',
2177 'RLRANum',
2178 'RLCustRefNum',
2179
2180 'RLPickupNumber'
2181 )
2182
2183 SELECT @ProcessRLItem = 1
2184 FROM #Column AS C
2185 WHERE C.CName IN
2186 (
2187 'RLProductName',
2188 'RLItemValue',
2189 'RLItemQuantity',
2190 'RLItemWeight',
2191 'RLSKU',
2192
2193 'RLDamaged',
2194 'RLAccepted',
2195 'RLSalvageable',
2196 'RLDisposition',
2197 'RLReason',
2198 'RLEventType',
2199 'RLErrorCode',
2200 'RLProductOperatingCompany',
2201 'RLShortCode',
2202 'RLComments'
2203 )
2204
2205 SELECT @ProcessRLSummaryItem = 1
2206 FROM #Column AS C
2207 WHERE C.CName IN
2208 (
2209 'RLSummaryValue',
2210 'RLSummaryQuantity'
2211 )
2212
2213 SELECT @ProcessDropTrailer = 1
2214 FROM #Column AS C
2215 WHERE C.CName IN
2216 (
2217 'DropTrailerShipper',
2218 'DropTrailerConsignee',
2219 'DropTrailerNotifiedByShipper',
2220 'DropTrailerNotifiedByConsignee',
2221 'ReceivedBy',
2222 'PiecesDelivered'
2223 )
2224
2225 SELECT @ProcessINCOTerm = 1
2226 FROM #Column AS C
2227 WHERE C.CName IN
2228 (
2229 'INCOTerm',
2230 'IncoTermLocation'
2231 )
2232
2233 SELECT @ProcessReasonCodes = 1
2234 FROM #Column AS C
2235 WHERE C.CName IN
2236 (
2237 'PLATEReason',
2238 'DLATEReason'
2239 )
2240
2241 SELECT @ProcessEPayments = 1
2242 FROM #Column AS C
2243 WHERE C.CName IN
2244 (
2245 'EPayApprovedBy',
2246 'EPayPaidBy',
2247 'EPayComments'
2248 )
2249
2250 SELECT @ProcessLoad = 1
2251 FROM #Column AS C
2252 WHERE C.CName IN(
2253 'LoadHotY',
2254 'CustomEquipmentType'
2255 )
2256
2257 --PurchaseOrder related stuff
2258 SELECT @ProcessPOCustomer = 1
2259 FROM #Column AS C
2260 WHERE C.CName IN(
2261 'POCustomerName'
2262 ,'CustomerAddress1'
2263 ,'CustomerAddress2'
2264 ,'CustomerCity'
2265 ,'CustomerState'
2266 ,'CustomerPostalCode'
2267 ,'CustomerAccountCode'
2268 )
2269 SELECT @ProcessPOBuyer = 1
2270 FROM #Column AS C
2271 WHERE C.CName IN(
2272 'BuyerName'
2273 ,'BuyerAddress1'
2274 ,'BuyerAddress2'
2275 ,'BuyerCity'
2276 ,'BuyerState'
2277 ,'BuyerPostalCode'
2278 ,'BuyerAccountCode'
2279 )
2280
2281 SELECT @ProcessPOEndCustomer = 1
2282 FROM #Column AS C
2283 WHERE C.CName IN(
2284 'EndCustomerName'
2285 ,'EndCustomerAddress1'
2286 ,'EndCustomerAddress2'
2287 ,'EndCustomerCity'
2288 ,'EndCustomerState'
2289 ,'EndCustomerPostalCode'
2290 ,'EndCustomerAccountCode'
2291 )
2292
2293 SELECT @ProcessPOImporter = 1
2294 FROM #Column AS C
2295 WHERE C.CName IN(
2296 'ImporterofRecordName'
2297 ,'ImporterofRecordAddress1'
2298 ,'ImporterofRecordAddress2'
2299 ,'ImporterofRecordCity'
2300 ,'ImporterofRecordState'
2301 ,'ImporterofRecordPostalCode'
2302 ,'ImporterofRecordAccountCode'
2303 )
2304
2305 SELECT @ProcessPOVendor = 1
2306 FROM #Column AS C
2307 WHERE C.CName IN(
2308 'POVendorName'
2309 ,'VendorAddress1'
2310 ,'VendorAddress2'
2311 ,'VendorCity'
2312 ,'VendorState'
2313 ,'VendorPostalCode'
2314 ,'VendorAccountCode'
2315 )
2316
2317 SELECT @ProcessPOManufacturer = 1
2318 FROM #Column AS C
2319 WHERE C.CName IN(
2320 'ManufacturerName'
2321 ,'ManufacturerAddress1'
2322 ,'ManufacturerAddress2'
2323 ,'ManufacturerCity'
2324 ,'ManufacturerState'
2325 ,'ManufacturerPostalCode'
2326 ,'ManufacturerAccountCode'
2327 )
2328
2329 SELECT @ProcessPOSeller = 1
2330 FROM #Column AS C
2331WHERE C.CName IN(
2332 'SellerName'
2333 ,'SellerAddress1'
2334 ,'SellerAddress2'
2335 ,'SellerCity'
2336 ,'SellerState'
2337 ,'SellerPostalCode'
2338 ,'SellerAccountCode'
2339)
2340
2341 SELECT @ProcessPOLocation = 1
2342 FROM #Column AS C
2343 WHERE C.CName IN(
2344 'OriginLocationName'
2345 ,'OriginLocationCity'
2346 ,'OriginLocationState'
2347 ,'OriginLocationCountry'
2348 ,'DestinationLocationName'
2349 ,'DestinationLocationCity'
2350 ,'DestinationLocationState'
2351 ,'DestinationLocationCountry'
2352 )
2353
2354 SELECT @ProcessPOItems = 1
2355 FROM #Column AS C
2356 WHERE C.CName IN(
2357 'InnerPackOriginalQuantity'
2358 ,'InnerPackQuantity'
2359 ,'InnerPackWeight'
2360 ,'InnerPackType'
2361 ,'InnerPackLength'
2362 ,'InnerPackWidth'
2363 ,'InnerPackHeight'
2364 ,'InnerPackVolume'
2365 ,'OuterPackStuffingQuantity'
2366 ,'OuterPackType'
2367 ,'OuterPackLength'
2368 ,'OuterPackWidth'
2369 ,'OuterPackHeight'
2370 ,'OuterPackVolume'
2371 ,'OuterPackWeight'
2372 ,'OuterPackQuantity'
2373 ,'POSKU'
2374 ,'POProductCode'
2375 ,'POHTCode'
2376 ,'ItemName'
2377 ,'TotalValue'
2378 ,'POMode'
2379 ,'POItemStatus'
2380 ,'POINCOTerm'
2381 ,'INCOLocation'
2382 ,'POStatus'
2383 ,'PlannedQuantity'
2384 ,'InTransitQuantity'
2385 ,'DeliveredQuantity'
2386 )
2387
2388 SELECT @ProcessPOItemReference = 1
2389 FROM #Column AS C
2390 WHERE C.CName IN(
2391 'POLineNumber'
2392 ,'VendorPONumber'
2393 ,'VendorLineNumber'
2394 ,'CustomerPONumber'
2395 ,'BuyerID'
2396 )
2397
2398 SELECT @ProcessPOItemDate = 1
2399 FROM #Column AS C
2400 WHERE C.CName IN(
2401 'RequestedBookingStartDate'
2402 ,'RequestedBookingDate'
2403 ,'ShipStartDate'
2404 ,'ShipEndDate'
2405 ,'RequestedPickupStartDate'
2406 ,'RequestedPickupDate'
2407 ,'RequestedDeliveryStartDate'
2408 ,'RequestedDeliveryDate'
2409 )
2410
2411 SELECT @ProcessCustomsCargoWise = 1
2412 FROM #Column AS C
2413 WHERE C.CName IN(
2414 'AgricultureHoldDate'
2415 ,'OGAFDAExamDate'
2416 )
2417
2418 SELECT @ProcessCOrderDates = 1
2419 FROM #Column AS C
2420 WHERE C.CName IN(
2421 'RecBookingDate'
2422 )
2423
2424 SELECT @ProcessDisplayShipmentNumbers = 1
2425 FROM #Column AS C
2426 WHERE C.CName IN
2427 (
2428 'DisplayLoadNumber',
2429 'DisplayCustomerOrderNumber'
2430 )
2431
2432 SELECT @ProcessOrderedSpace = 1
2433 FROM #Column AS C
2434 WHERE C.CName IN
2435 (
2436 'OrderedSpace'
2437 )
2438
2439 -- =======================================================
2440 -- Build #SPODetailID
2441 -- =======================================================
2442
2443 IF
2444 @ProcessDriverTixSummaries = 1 OR
2445 @ProcessFUDates = 1 OR
2446 @ProcessLFUDates = 1 OR
2447 @ProcessMisc = 1 OR
2448 @ProcessPOD = 1 OR
2449 @ProcessPoolCrossLocationDates = 1
2450BEGIN
2451 CREATE TABLE #SPODetailID
2452 (
2453 COSDetailID INT,
2454 SPODetailID INT
2455 )
2456
2457 CREATE CLUSTERED INDEX INX_SPODetailID ON #SPODetailID(COSDetailID)
2458
2459 INSERT INTO #SPODetailID(COSDetailID, SPODetailID)
2460 SELECT R.COSDetailID, P.SPODetailID
2461 FROM #Row AS R
2462 INNER JOIN PDetail AS P WITH(NOLOCK)
2463 ON R.COSDetailID = P.COSDetailID
2464
2465 END
2466
2467 -- =====================================================================================================================
2468 -- Build temp tables required for dates
2469 -- =====================================================================================================================
2470
2471 IF @ProcessFUDates = 1 OR @ProcessLFUDates = 1 OR @ProcessPoolCrossLocationDates = 1
2472 BEGIN
2473
2474 CREATE TABLE #DateTimeMapping
2475 (
2476 NameInColumnTable VARCHAR(50),
2477 NameInSourceTable VARCHAR(50)
2478 )
2479
2480 CREATE CLUSTERED INDEX INX_DateTimeMapping_NameInSourceTable ON #DateTimeMapping(NameInSourceTable)
2481
2482 INSERT INTO [#DateTimeMapping] (NameInColumnTable,NameInSourceTable)
2483 SELECT 'EnterTime', 'Enter Time' UNION ALL
2484
2485 SELECT 'EarliestReqPickupTime', 'Earliest Requested Pickup Time' UNION ALL
2486 SELECT 'LatestReqPickupTime', 'Latest Requested Pickup Time' UNION ALL
2487 SELECT 'EarliestSchedPickupTime', 'Earliest Scheduled Pickup Time' UNION ALL
2488 SELECT 'LatestSchedPickupTime', 'Latest Scheduled Pickup Time' UNION ALL
2489 SELECT 'EarliestActualPickupTime', 'Arrival Pickup Time' UNION ALL
2490 SELECT 'LatestActualPickupTime', 'Latest Actual Pickup Time' UNION ALL
2491SELECT 'ShipperDropTrailerArrivalTime', 'Drop Trailer Arrival Time Shipper' UNION ALL
2492 SELECT 'ShipperDropTrailerReadyTime', 'Drop Trailer Ready Time Shipper' UNION ALL
2493 SELECT 'EarliestReqDeliveryTime', 'Earliest Requested Delivery Time' UNION ALL
2494 SELECT 'LatestReqDeliveryTime', 'Latest Requested Delivery Time' UNION ALL
2495 SELECT 'EarliestSchedDeliveryTime', 'Earliest Scheduled Delivery Time' UNION ALL
2496 SELECT 'LatestSchedDeliveryTime', 'Latest Scheduled Delivery Time' UNION ALL
2497 SELECT 'EarliestActualDeliveryTime', 'Arrival Delivery Time' UNION ALL
2498 SELECT 'LatestActualDeliveryTime', 'Latest Actual Delivery Time' UNION ALL
2499 SELECT 'ConsigneeDropTrailerArrivalTime', 'Drop Trailer Arrival Time Consignee' UNION ALL
2500 SELECT 'ConsigneeDropTrailerReadyTime', 'Drop Trailer Ready Time Consignee' UNION ALL
2501 SELECT 'PoolpointSchedArrivalTime', 'Poolpoint Scheduled Arrival Time' UNION ALL
2502 SELECT 'PoolpointSchedDepartTime', 'Poolpoint Scheduled Departure Time' UNION ALL
2503 SELECT 'PoolpointActualArrivalTime', 'Poolpoint Actual Arrival Time' UNION ALL
2504 SELECT 'PoolpointActualDepartTime', 'Poolpoint Actual Departure Time' UNION ALL
2505 SELECT 'CrossDockArrivalTime', 'Cross Dock Actual Arrival Time' UNION ALL
2506 SELECT 'CrossDockSchedDepartTime', 'Cross Dock Scheduled Departure Time' UNION ALL
2507 SELECT 'CrossDockActualDepartTime', 'Cross Dock Actual Departure Time' UNION ALL
2508 SELECT 'OrigTerminalArrivalTime', 'Origin Terminal Arrival Time' UNION ALL
2509 SELECT 'OrigTerminalDepartTime', 'Origin Terminal Departure Time' UNION ALL
2510 SELECT 'OrigRampCutOffTime', 'Origin Ramp Cutoff Time' UNION ALL
2511 SELECT 'OrigRampArrivalTime', 'Origin Ramp Arrival Time' UNION ALL
2512 SELECT 'OrigRampRampedTime', 'Origin Ramp Ramped Time' UNION ALL
2513 SELECT 'DestRampArrivalTime', 'Destination Ramp Arrival Time' UNION ALL
2514 SELECT 'DestRampDeRampedTime', 'Destination Ramp Deramped Time' UNION ALL
2515 SELECT 'DestTerminalArrivalTime', 'Destination Terminal Arrival Time' UNION ALL
2516 SELECT 'DestTerminalDepartTime', 'Destination Terminal Departure Time' UNION ALL
2517
2518SELECT 'EnterDate', 'Enter Date' UNION ALL
2519
2520 SELECT 'EarliestReqPickupDate', 'Earliest Requested Pickup Date' UNION ALL
2521 SELECT 'LatestReqPickupDate', 'Latest Requested Pickup Date' UNION ALL
2522 SELECT 'EarliestSchedPickupDate', 'Earliest Scheduled Pickup Date' UNION ALL
2523 SELECT 'LatestSchedPickupDate', 'Latest Scheduled Pickup Date' UNION ALL
2524 SELECT 'EarliestActualPickupDate', 'Arrival Pickup Date' UNION ALL
2525 SELECT 'LatestActualPickupDate', 'Latest Actual Pickup Date' UNION ALL
2526 SELECT 'ShipperDropTrailerArrivalDate', 'Drop Trailer Arrival Date Shipper' UNION ALL
2527 SELECT 'ShipperDropTrailerReadyDate', 'Drop Trailer Ready Date Shipper' UNION ALL
2528 SELECT 'EarliestReqDeliveryDate', 'Earliest Requested Delivery Date' UNION ALL
2529 SELECT 'LatestReqDeliveryDate', 'Latest Requested Delivery Date' UNION ALL
2530 SELECT 'EarliestSchedDeliveryDate', 'Earliest Scheduled Delivery Date' UNION ALL
2531 SELECT 'LatestSchedDeliveryDate', 'Latest Scheduled Delivery Date' UNION ALL
2532 SELECT 'EarliestActualDeliveryDate', 'Arrival Delivery Date' UNION ALL
2533 SELECT 'LatestActualDeliveryDate', 'Latest Actual Delivery Date' UNION ALL
2534 SELECT 'ConsigneeDropTrailerArrivalDate', 'Drop Trailer Arrival Date Consignee' UNION ALL
2535 SELECT 'ConsigneeDropTrailerReadyTime', 'Drop Trailer Ready Date Consignee' UNION ALL
2536 SELECT 'PoolpointSchedArrivalDate', 'Poolpoint Scheduled Arrival Date' UNION ALL
2537 SELECT 'PoolpointSchedDepartDate', 'Poolpoint Scheduled Departure Date' UNION ALL
2538 SELECT 'PoolpointActualArrivalDate', 'Poolpoint Actual Arrival Date' UNION ALL
2539 SELECT 'PoolpointActualDepartDate', 'Poolpoint Actual Departure Date' UNION ALL
2540 SELECT 'CrossDockArrivalDate', 'Cross Dock Actual Arrival Date' UNION ALL
2541 SELECT 'CrossDockSchedDepartDate', 'Cross Dock Scheduled Departure Date' UNION ALL
2542 SELECT 'CrossDockActualDepartDate', 'Cross Dock Actual Departure Date' UNION ALL
2543 SELECT 'OrigTerminalETADate', 'Origin Terminal ETA Date' UNION ALL
2544 SELECT 'OrigTerminalArrivalDate', 'Origin Terminal Arrival Date' UNION ALL
2545 SELECT 'OrigTerminalDepartDate', 'Origin Terminal Departure Date' UNION ALL
2546 SELECT 'OrigRampCutOffDate', 'Origin Ramp Cutoff Date' UNION ALL
2547 SELECT 'OrigRampArrivalDate', 'Origin Ramp Arrival Date' UNION ALL
2548 SELECT 'OrigRampRampedDate', 'Origin Ramp Ramped Date' UNION ALL
2549 SELECT 'DestRampArrivalDate', 'Destination Ramp Arrival Date' UNION ALL
2550 SELECT 'DestRampDeRampedDate', 'Destination Ramp Ramped Date' UNION ALL
2551 SELECT 'DestTerminalArrivalDate', 'Destination Terminal Arrival Date' UNION ALL
2552 SELECT 'DestTerminalDepartDate', 'Destination Terminal Departure Date' UNION ALL
2553 SELECT 'PortCutoffDate', 'Port Cutoff Date' UNION ALL
2554 SELECT 'OriginalPortETDDate', 'Original Port ETD Date' UNION ALL
2555 SELECT 'PortETDDate', 'Port ETD Date' UNION ALL
2556 SELECT 'OriginalPortETADate', 'Original Port ETA Date' UNION ALL
2557 SELECT 'PortETADate', 'Port ETA Date' UNION ALL
2558 SELECT 'ActualPortArrivalDate', 'Actual Port Arrival Date' UNION ALL
2559 SELECT 'ActualPortDepartDate', 'Actual Port Departure Date' UNION ALL
2560 SELECT 'IMDLPromiseDate', 'IMDL Promise Date' UNION ALL
2561 SELECT 'DeliveryOrderCreatedDate', 'Delivery Order Created Date' UNION ALL
2562 SELECT 'RailETADate', 'Rail ETA Date' UNION ALL
2563 SELECT 'DestRampETADate', 'Destination Ramp ETA Date' UNION ALL
2564 SELECT 'EmptyReturnDate', 'EmptyReturnDate' UNION ALL
2565 SELECT 'LastFreeDate', 'LastFreeDate'
2566
2567 --CREATE CLUSTERED INDEX INX_DateTimeMapping_NameInSourceTable ON #DateTimeMapping(NameInSourceTable)
2568
2569 CREATE TABLE #UnpivotedCOServiceDates
2570 (
2571 COServiceID INT,
2572 DateTimeType VARCHAR(100),
2573 DateTimeValue INT
2574 )
2575
2576 CREATE TABLE #UnpivotedCOLocationDates
2577 (
2578 COLocationID INT,
2579 DateTimeType VARCHAR(100),
2580 DateTimeValue INT
2581 )
2582
2583 CREATE TABLE #UnpivotedSPODLocationDates
2584 (
2585 SPODLocationID INT,
2586 KeyLocationID INT,
2587 DateTimeType VARCHAR(100),
2588 DateTimeValue INT
2589 )
2590
2591 CREATE TABLE #UnpivotedSPODates
2592 (
2593 SPOrderID INT,
2594 DateTimeType VARCHAR(100),
2595 DateTimeValue INT
2596 )
2597
2598 CREATE TABLE #UnpivotedLoadDates
2599 (
2600 LoadID INT,
2601 DateTimeType VARCHAR(100),
2602 DateTimeValue INT
2603 )
2604
2605 --PRINT 'Load UnpivotedCOLocationDates'
2606
2607 INSERT INTO #UnpivotedCOServiceDates (COServiceID, DateTimeType, DateTimeValue)
2608 SELECT
2609 UP.COServiceID,
2610 CASE UP.SourceDateTimeColumn
2611 WHEN 'TimeValue' THEN REPLACE(UP.DateType, 'Date', 'Time')
2612 ELSE UP.DateType
2613 END,
2614 UP.DateTimeValue
2615 FROM
2616 (
2617 SELECT R.COServiceID, CSD.DateType, CSD.DateValue, CSD.TimeValue
2618 FROM #Row AS R
2619 INNER JOIN dbo.COServiceDate AS CSD WITH (NOLOCK)
2620 ON R.COServiceID = CSD.COServiceID
2621 WHERE CSD.DateType = 'Enter Date' -- change to same sql as below if we ever add more coservicedate time columns here
2622 ) as p
2623 UNPIVOT (
2624 DateTimeValue FOR SourceDateTimeColumn IN
2625 (
2626 p.DateValue,
2627 p.TimeValue
2628 )
2629 ) AS up
2630
2631 OPTION(LOOP JOIN)
2632
2633 INSERT INTO [#UnpivotedCOLocationDates] (COLocationID,DateTimeType,DateTimeValue)
2634 SELECT
2635 UP.COLocationID,
2636 CASE UP.SourceDateTimeColumn
2637 WHEN 'TimeValue' THEN REPLACE(UP.DateType,'Date','Time')
2638 ELSE UP.DateType END,
2639 UP.TheDateTimeType
2640
2641 FROM
2642 (
2643 SELECT CD.COLocationID, CD.DateType, CD.DateValue, CD.TimeValue
2644 FROM #Row AS R
2645 INNER JOIN COLocation AS L WITH(NOLOCK)
2646 ON R.COSDetailID = L.COSDetailID
2647 INNER JOIN COLocationDate AS CD WITH(NOLOCK)
2648 ON L.COLocationID = CD.COLocationID
2649 WHERE EXISTS (SELECT 1 FROM [#DateTimeMapping] AS DM
2650 INNER JOIN #Column AS C
2651 ON DM.NameInColumnTable = C.CName
2652 WHERE CD.DateType = DM.NameInSourceTable)
2653 ) as p
2654
2655 UNPIVOT
2656 (
2657 TheDateTimeType FOR SourceDateTimeColumn IN
2658 (
2659 p.DateValue,
2660 p.TimeValue
2661 )
2662 ) AS up
2663
2664 OPTION(LOOP JOIN)
2665
2666 -- ========================================================================================
2667
2668 --PRINT 'Load UnpivotedSPODLocationDates'
2669/*<><><><><><><>Jeremy Dixon change 12/11/2013<><><><><><><>*/
2670
2671 INSERT INTO #SPODLocationDates_capture
2672 (SPODLocationID
2673 ,KeyLocationID
2674 ,DateType
2675 ,DateValue
2676 ,TimeValue)
2677 SELECT LD.SPODLocationID, SL.KeyLocationID, LD.DateType, LD.DateValue, LD.TimeValue
2678 FROM #Row AS R
2679 INNER JOIN #SPODetailID S (NOLOCK) ON S.COSDetailID = R.COSDetailID
2680 INNER JOIN SPODLocation AS SL WITH(NOLOCK)
2681 ON SL.SPODetailID = S.SPODetailID
2682 INNER JOIN SPODLocationDate AS LD WITH(NOLOCK)
2683 ON SL.SPODLocationID = LD.SPODLocationID
2684
2685/*<><><><><><><>Jeremy Dixon change 12/11/2013<><><><><><><>*/
2686 INSERT INTO [#UnpivotedSPODLocationDates] (SPODLocationID, KeyLocationID, DateTimeType,DateTimeValue)
2687 SELECT
2688 UP.SPODLocationID,
2689 UP.KeyLocationID,
2690 CASE UP.SourceDateTimeColumn
2691 WHEN 'TimeValue' THEN REPLACE(UP.DateType,'Date','Time')
2692 ELSE UP.DateType END,
2693 UP.TheDateTimeType
2694
2695 FROM
2696 (
2697 SELECT LD.SPODLocationID, LD.KeyLocationID, LD.DateType, LD.DateValue, LD.TimeValue
2698 FROM #SPODLocationDates_capture AS LD
2699 WHERE EXISTS (SELECT 1 FROM [#DateTimeMapping] AS DM
2700 INNER JOIN #Column AS C WITH(NOLOCK)
2701 ON DM.NameInColumnTable = C.CName
2702 WHERE LD.DateType = DM.NameInSourceTable)
2703 ) as p
2704
2705 UNPIVOT
2706 (
2707 TheDateTimeType FOR SourceDateTimeColumn IN
2708 (
2709 p.DateValue,
2710 p.TimeValue
2711 )
2712 ) AS up
2713
2714 -- ========================================================================================
2715
2716 --PRINT 'Load UnpivotedSPODates'
2717 /*<><><><><><><>Jeremy Dixon change 12/11/2013<><><><><><><>*/
2718INSERT INTO #SPODates_capture
2719 (SPOrderID
2720 ,DateType
2721 ,DateValue
2722 ,TimeValue)
2723SELECT OD.SPOrderID, OD.DateType, OD.DateValue, OD.TimeValue
2724 FROM #Row AS R
2725 INNER JOIN #SPODetailID AS PD
2726 ON R.COSDetailID = PD.COSDetailID
2727 INNER JOIN SPODetail AS SPOD WITH(NOLOCK)
2728 ON PD.SPODetailID = SPOD.SPODetailID
2729 INNER JOIN SPOrderDate AS OD WITH(NOLOCK)
2730 ON SPOD.SPOrderID = OD.SPOrderID
2731 INNER JOIN SPOrder AS O WITH(NOLOCK)
2732 ON OD.SPOrderID = O.SPOrderID
2733WHERE ISNULL(O.ShipmentType,'H') = 'H'
2734
2735/*<><><><><><><>Jeremy Dixon change 12/11/2013<><><><><><><>*/
2736INSERT INTO [#UnpivotedSPODates] (SPOrderID,DateTimeType,DateTimeValue)
2737 SELECT
2738 UP.SPOrderID,
2739 CASE UP.SourceDateTimeColumn
2740 WHEN 'TimeValue' THEN REPLACE(UP.DateType,'Date','Time')
2741 ELSE UP.DateType END,
2742 UP.TheDateTimeType
2743
2744 FROM
2745 (
2746 SELECT OD.SPOrderID, OD.DateType, OD.DateValue, OD.TimeValue
2747 FROM #SPODates_capture AS OD
2748 WHERE EXISTS (SELECT 1 FROM [#DateTimeMapping] AS DM
2749 INNER JOIN #Column AS C
2750 ON DM.NameInColumnTable = C.CName
2751 WHERE OD.DateType = DM.NameInSourceTable)
2752
2753 ) as p
2754
2755 UNPIVOT
2756 (
2757 TheDateTimeType FOR SourceDateTimeColumn IN
2758 (
2759 p.DateValue,
2760 p.TimeValue
2761 )
2762 ) AS up
2763
2764 INSERT INTO #UnpivotedLoadDates (LoadID, DateTimeType, DateTimeValue)
2765 SELECT
2766 UP.LoadID,
2767 CASE UP.SourceDateTimeColumn
2768 WHEN 'TimeValue' THEN REPLACE(UP.DateType, 'Date', 'Time')
2769 ELSE UP.DateType
2770 END,
2771 UP.DateTimeValue
2772 FROM
2773 (
2774 SELECT LDE.LoadID, LDE.DateType, LDE.DateValue, LDE.TimeValue
2775 FROM #Row AS R
2776 INNER JOIN dbo.LoadDate AS LDE WITH (NOLOCK)
2777 ON R.LoadID = LDE.LoadID
2778 WHERE EXISTS (SELECT 1 FROM [#DateTimeMapping] AS DM
2779 INNER JOIN #Column AS C
2780 ON DM.NameInColumnTable = C.CName
2781 WHERE LDE.DateType = DM.NameInSourceTable)
2782 ) as p
2783 UNPIVOT (
2784 DateTimeValue FOR SourceDateTimeColumn IN
2785 (
2786 p.DateValue,
2787 p.TimeValue
2788 )
2789 ) AS up
2790
2791 OPTION(LOOP JOIN)
2792
2793 DROP TABLE #DateTimeMapping
2794
2795 END
2796
2797 -- =====================================================================================================================
2798 -- LOAD TEMP TABLES WITH DATA
2799 -- =====================================================================================================================
2800
2801 -- OK02062008========================================================================================
2802 -- Load Alerts
2803 -- ==================================================================================================
2804
2805 --PRINT 'Load Alerts'
2806
2807 IF @ProcessAlerts = 1
2808 BEGIN
2809 INSERT INTO #Alert(Alert_RecordID, EnteredDate, TheDate, Description, ActiveFlg)
2810 SELECT
2811 R.RecordID AS Alert_RecordID
2812 ,CASE A.ActiveFlg
2813 WHEN 1 THEN 'Active_' + CONVERT(VARCHAR, MAX(A.EnteredDate), 120)
2814 WHEN 0 THEN 'Closed_' + CONVERT(VARCHAR, MAX(A.ClosedDate), 120)
2815 END AS EnteredDate
2816 ,MAX(A.EnteredDate) AS TheDate
2817 --1/24/11 - suggmic - added exception for 'Truck Ordered Not Used' used in both itemized access and ship alerts
2818 ,CASE WHEN A.Code = 'TONU' THEN A.Description + ' (Shipment Alert)' ELSE SUBSTRING(A.Description, 1, 125) END AS Description
2819 ,A.ActiveFlg
2820 FROM #Row AS R
2821 INNER JOIN COSAlert AS CS WITH(NOLOCK)
2822 ON R.COServiceID = CS.COServiceID
2823 INNER JOIN Alert AS A WITH(NOLOCK)
2824 ON CS.AlertID = A.AlertID
2825 GROUP BY R.RecordID, A.Description, A.Code, A.ActiveFlg
2826
2827 -- 09/15/2009 GANASAD GFS shipment level alerts
2828 UNION
2829
2830 SELECT
2831 R.RecordID AS Alert_RecordID
2832 ,CASE A.ActiveFlg
2833 WHEN 1 THEN 'Active_' + CONVERT(VARCHAR, MAX(A.EnteredDate), 120)
2834 WHEN 0 THEN 'Closed_' + CONVERT(VARCHAR, MAX(A.ClosedDate), 120)
2835 END AS EnteredDate
2836 ,MAX(A.EnteredDate) AS TheDate
2837 --1/24/11 - suggmic - added exception for 'Truck Ordered Not Used' used in both itemized access and ship alerts
2838 ,CASE WHEN A.Code = 'TONU' THEN A.Description + ' (Shipment Alert)' ELSE SUBSTRING(A.Description, 1, 125) END AS Description
2839 ,A.ActiveFlg
2840 FROM
2841 #Row AS R
2842 INNER JOIN
2843 dbo.COSGroup AS G WITH(NOLOCK)
2844 ON R.COSGroupID = G.COSGroupID
2845 INNER JOIN
2846 dbo.COService AS C WITH(NOLOCK)
2847 ON C.FirstLoadNumber = G.PrimaryLoadNumber
2848 INNER JOIN
2849 dbo.COSAlert AS CA WITH(NOLOCK)
2850 ON C.COServiceID = CA.COServiceID
2851 INNER JOIN
2852 dbo.Alert AS A WITH(NOLOCK)
2853 ON CA.AlertID = A.AlertID
2854 WHERE
2855 A.ShipmentLevelFlag = 1
2856 GROUP BY R.RecordID, A.Description, A.Code, A.ActiveFlg
2857
2858 -- If we have multiple problems for the same code that are closed/active, show
2859 -- only active ones.
2860 DELETE A2
2861 FROM #Alert AS A2
2862 INNER JOIN
2863 (
2864 SELECT
2865 A.Alert_RecordID, Description
2866 FROM #Alert AS A
2867 GROUP BY Alert_RecordID, Description
2868 HAVING COUNT(DISTINCT ActiveFlg) > 1
2869 ) AS T
2870 ON A2.Alert_RecordID = T.Alert_RecordID AND A2.Description = T.Description AND A2.ActiveFlg = 0
2871
2872 -- If we have multiple closed alerts for the same code, show only the latest one.
2873 DELETE A2
2874 FROM #Alert AS A2
2875 INNER JOIN
2876 (
2877 SELECT
2878 Alert_RecordID, Description, MAX(TheDate) AS TheDate
2879 FROM #Alert AS A
2880 GROUP BY Alert_RecordID, Description
2881 HAVING COUNT(DISTINCT ActiveFlg) = 1 AND COUNT(ActiveFlg) > 1
2882 ) AS T
2883 ON A2.Alert_RecordID = T.Alert_RecordID AND A2.Description = T.Description AND A2.TheDate <> T.TheDate
2884
2885 -- Set TheDate/ActiveFlg to NULL so that it doesn't interfere with the PIVOT at the end of the sproc
2886 UPDATE #Alert SET TheDate = NULL
2887 UPDATE #Alert SET ActiveFlg = NULL
2888 END
2889
2890 -- =============================================================================================
2891 -- Load #Payers
2892 -- =============================================================================================
2893
2894 --PRINT 'Load Payers'
2895
2896 IF @ProcessPayers = 1
2897 BEGIN
2898 INSERT INTO [#Payer]
2899 (
2900 PayerNumber,
2901 Payer_RecordID,
2902 PayerName,
2903 PayerLocationID,
2904 PartyNumber
2905 )
2906 SELECT
2907 ROW_NUMBER() OVER (PARTITION BY R.RecordID ORDER BY R.RecordID) AS PayerNumber,
2908 R.RecordID AS Payer_RecordID,
2909 OP.[Name] AS PayerName,
2910 OP.PartyCode AS PayerLocationID,
2911 OP.PartyNumber AS PartyNumber
2912 FROM [#Row] AS R
2913 INNER JOIN COServiceParty AS CP WITH(NOLOCK)
2914 ON R.COServiceID = CP.COServiceID
2915 INNER JOIN OrderParty AS OP WITH(NOLOCK)
2916 ON CP.OrderPartyID = OP.OrderPartyID AND OP.[Role]='BILLTO'
2917 INNER JOIN #UserCCodes AS CC
2918 ON OP.PartyCode = CC.CompanyCode
2919
2920 GROUP BY R.RecordID, OP.[Name], OP.PartyCode, OP.PartyNumber
2921
2922 UPDATE
2923 tp
2924 SET
2925 tp.PayerAddress1 = PA.[Address1],
2926 tp.PayerAddress2 = PA.[Address2],
2927 tp.PayerCity = PA.[City],
2928 tp.PayerState = PA.[State],
2929 tp.PayerZip = PA.[PostalCode]
2930 FROM
2931#Payer AS tp
2932 INNER JOIN
2933 MDMPublicReadOnly.mdm.Party AS P WITH(NOLOCK)
2934 ON tp.PartyNumber = p.PartyNumber
2935 INNER JOIN
2936 MDMPublicReadOnly.mdm.PartyAddress AS PA WITH(NOLOCK)
2937 ON tp.PartyNumber = PA.PartyNumber
2938-- AND PA.AddressTypeRDN = 17 -- 10/03/2008 GANASAD MDM team is making changes that's causing a lot of party addresses to be deleted
2939 AND PA.PartyAddressTypeID = 2 -- Company address
2940 AND PA.Deleted = 0
2941
2942 UPDATE
2943 TP
2944 SET
2945 tp.PayerAddress1 = SUBSTRING(C.Address1, 1, 50),
2946 tp.PayerAddress2 = SUBSTRING(C.Address2, 1, 50),
2947 tp.PayerCity = C.City,
2948 tp.PayerState = C.State,
2949 tp.PayerZip = C.Zip
2950 FROM
2951 #Row AS R
2952 INNER JOIN
2953 #Payer AS TP
2954 ON R.RecordID = TP.Payer_RecordID
2955 INNER JOIN
2956 EUCommon.dbo.CustomersEU AS C WITH(NOLOCK)
2957 ON SUBSTRING(TP.PayerLocationID, 1, 10) = C.CompanyCode -- GANASAD We're doing SUBSTRING because PayerLocationID (i.e., PartyCode)
2958 -- can be up to varchar(50) to accomodate for the different party codes
2959 -- stored in OrderParty. CustomerCode will always be ten or fewer chars
2960 -- long.
2961 WHERE
2962 R.SourceTypeID = 4
2963 END
2964
2965 -- =============================================================================================
2966 -- Load #MethodOfPayment
2967 -- =============================================================================================
2968
2969 IF @ProcessMethodsOfPayment = 1
2970 BEGIN
2971 INSERT INTO #MethodOfPayment(MethodOfPayment_RecordID, MethodOfPayment)
2972 SELECT
2973 R.RecordID,
2974 (
2975 SELECT DISTINCT MethodOfPayment + ', '
2976 FROM #Row AS R2
2977 INNER JOIN COServiceParty AS P WITH(NOLOCK)
2978 ON R2.COServiceID = P.COServiceID
2979 WHERE R2.RecordID = R.RecordID
2980 FOR XML PATH('')
2981 ) AS MethodOfPayment
2982 FROM #Row AS R
2983 INNER JOIN COServiceParty AS P2 WITH(NOLOCK)
2984 ON R.COServiceID = P2.COServiceID
2985 GROUP BY R.RecordID
2986 HAVING COUNT(DISTINCT P2.MethodOfPayment) > 1
2987
2988 -- Process one-on-one when there is only one method of payment
2989 INSERT INTO #MethodOfPayment(MethodOfPayment_RecordID, MethodOfPayment)
2990 SELECT
2991 R.RecordID,
2992 P2.MethodOfPayment
2993 FROM #Row AS R
2994 INNER JOIN COServiceParty AS P2 WITH(NOLOCK)
2995 ON R.COServiceID = P2.COServiceID
2996 LEFT OUTER JOIN #MethodOfPayment AS M
2997 ON R.RecordID = M.MethodOfPayment_RecordID
2998 WHERE M.MethodOfPayment_RecordID IS NULL
2999 END
3000
3001 -- OK02062008=============================================================================================
3002 -- Load #SpecialInstructions
3003 -- =======================================================================================================
3004
3005 --PRINT 'Load special instructions'
3006
3007 IF @ProcessSpecialInstructions = 1 AND (@SummarizeShipment = 0 OR @SummarizeOcean = 0)
3008 BEGIN
3009 INSERT INTO #SpecialInstructions(SpecialInstructions_RecordID, OrigSpecialInstructions,DestSpecialInstructions)
3010 SELECT DISTINCT
3011 R.RecordID AS SpecialInstructions_RecordID,
3012 OrigN.SpecialInstruction AS OrigSpecialInstructions,
3013 DestN.SpecialInstruction AS DestSpecialInstructions
3014 FROM #Row AS R
3015 LEFT OUTER JOIN PDLocation AS OrigP WITH(NOLOCK)
3016 ON R.OriginCOLocationID = OrigP.COLocationID
3017 LEFT OUTER JOIN PDLocation AS DestP WITH(NOLOCK)
3018 ON R.DestCOLocationID = DestP.COLocationID
3019 LEFT OUTER JOIN SPODLocationNote AS OrigN WITH(NOLOCK)
3020 ON OrigP.SPODLocationID = OrigN.SPODLocationID
3021 LEFT OUTER JOIN SPODLocationNote AS DestN WITH(NOLOCK)
3022 ON DestP.SPODLocationID = DestN.SPODLocationID
3023 WHERE R.LevelNumber = 1
3024 -- R.LevelNumber = 1 ensures that we do not populate special
3025 -- instructions for recordids that are part of a summary shipment
3026 -- summary shipments do not have a value for special instructions
3027 END
3028
3029-- OK02062008=============================================================================================
3030 -- Load #CustomerLocation
3031 -- =======================================================================================================
3032
3033 -- We need to create customer locations if we want to process dates because we
3034 -- need to know the origin stop number and destination stop number so we can get
3035 -- the appropriate dates for the appropriate location types (ie, origin dates for
3036 -- origin locations and destination (delivery) dates for destination locations).
3037 IF @ProcessCustomerLocations = 1 OR @ProcessFUDates = 1
3038 BEGIN
3039 INSERT INTO #CustomerLocation
3040 (
3041 CustomerLocation_RecordID
3042 ,OriginStopNumber
3043 ,DestStopNumber
3044 ,OrigName
3045 ,OrigAddress1
3046 ,OrigAddress2
3047 ,OrigCity
3048 ,OrigState
3049 ,OrigCountry
3050 ,OrigZip
3051 ,OrigLocationID
3052 ,OrigAirportCode
3053 ,DestName
3054 ,DestAddress1
3055 ,DestAddress2
3056 ,DestCity
3057 ,DestState
3058 ,DestCountry
3059 ,DestZip
3060 ,DestLocationID
3061 ,DestAirportCode
3062 )
3063
3064 SELECT
3065 R.RecordID AS CustomerLocation_RecordID,
3066 R.OriginStopNumber AS OriginStopNumber,
3067 R.DestStopNumber AS DestStopNumber,
3068 ORIG.[Name] AS OrigName,
3069 ORIG.Address1 AS OrigAddress1,
3070 ORIG.Address2 AS OrigAddress2,
3071 ORIG.City AS OrigCity,
3072 ORIG.State AS OrigState,
3073 ORIG.Country AS OrigCountry,
3074 ORIG.PostalCode As OrigZip,
3075 R.OriginLocationPartyNumber AS OrigLocationID,
3076 ORIG.AirportCode AS OrigAirportCode,
3077 DEST.[Name] AS DestName,
3078 DEST.Address1 AS DestAddress1,
3079 DEST.Address2 AS DestAddress2,
3080 DEST.City AS DestCity,
3081 DEST.State AS DestState,
3082 DEST.Country AS DestCountry,
3083 DEST.PostalCode As DestZip,
3084 R.DestLocationPartyNumber AS DestLocationID,
3085 DEST.AirportCode AS DestAirportCode
3086
3087 FROM #Row AS R
3088 LEFT OUTER JOIN NTSR.dbo.DimLocation AS ORIG WITH(NOLOCK)
3089 ON R.OriginKeyLocationID = ORIG.KeyLocationID
3090 LEFT OUTER JOIN NTSR.dbo.DimLocation AS DEST WITH(NOLOCK)
3091 ON R.DestKeyLocationID = DEST.KeyLocationID
3092 WHERE R.LevelNumber = 1
3093
3094 IF @SummarizeShipment = 0 AND EXISTS(SELECT TOP 1 1 FROM #Row WHERE SourceTypeID = 2)
3095 BEGIN
3096 UPDATE #CustomerLocation
3097 SET OrigName = P.Name,
3098 OrigCity = A.City,
3099 OrigState = A.[State],
3100 OrigZip = A.PostalCode,
3101 OrigCountry = A.Country,
3102 OrigAddress1 = A.Address1,
3103 OrigAddress2 = A.Address2,
3104 OrigAirportCode = ''
3105 FROM #CustomerLocation CL
3106 INNER JOIN #Row R ON CL.CustomerLocation_RecordID = R.RecordID
3107 INNER JOIN COLocation L WITH(NOLOCK) ON L.COSDetailID = R.COSDetailID
3108 INNER JOIN MDMPublicReadOnly.mdm.Party AS P WITH(NOLOCK) ON L.PaperworkLocationNumber = P.PartyNumber
3109 INNER JOIN MDMPublicReadOnly.mdm.PartyAddress A WITH(NOLOCK) ON L.PaperworkAddressNumber = A.AddressNumber
3110 WHERE R.SourceTypeId = 2 AND L.COLocationType IN ('P', 'XP')
3111
3112 UPDATE #CustomerLocation
3113 SET DestName = P.Name,
3114 DestCity = A.City,
3115 DestState = A.[State],
3116 DestZip = A.PostalCode,
3117 DestCountry = A.Country,
3118 DestAddress1 = A.Address1,
3119 DestAddress2 = A.Address2,
3120 DestAirportCode = ''
3121 FROM #CustomerLocation CL
3122 INNER JOIN #Row R ON CL.CustomerLocation_RecordID = R.RecordID
3123 INNER JOIN COLocation L WITH(NOLOCK) ON L.COSDetailID = R.COSDetailID
3124 INNER JOIN MDMPublicReadOnly.mdm.Party AS P WITH(NOLOCK) ON L.PaperworkLocationNumber = P.PartyNumber
3125 INNER JOIN MDMPublicReadOnly.mdm.PartyAddress A WITH(NOLOCK) ON L.PaperworkAddressNumber = A.AddressNumber
3126 WHERE R.SourceTypeId = 2 AND L.COLocationType IN ('D', 'XD')
3127 END
3128
3129 -- Candidate for optimization
3130 IF @SummarizeShipment = 1
3131 BEGIN
3132 INSERT INTO #CustomerLocation
3133 (
3134 CustomerLocation_RecordID
3135 ,OriginStopNumber
3136 ,DestStopNumber
3137 ,OrigName
3138 ,OrigAddress1
3139 ,OrigAddress2
3140 ,OrigCity
3141 ,OrigState
3142 ,OrigCountry
3143 ,OrigZip
3144 ,OrigLocationID
3145 ,OrigAirportCode
3146 ,DestName
3147 ,DestAddress1
3148 ,DestAddress2
3149 ,DestCity
3150 ,DestState
3151 ,DestCountry
3152 ,DestZip
3153 ,DestLocationID
3154 ,DestAirportCode
3155 )
3156 SELECT DISTINCT
3157 S.RecordID AS CustomerLocation_RecordID,
3158 S.OriginStopNumber AS OriginStopNumber,
3159 S.DestStopNumber AS DestStopNumber,
3160 ORIG.[Name] AS OrigName,
3161 ORIG.Address1 AS OrigAddress1,
3162 ORIG.Address2 AS OrigAddress2,
3163 ORIG.City AS OrigCity,
3164 ORIG.State AS OrigState,
3165 ORIG.Country AS OrigCountry,
3166 ORIG.PostalCode As OrigZip,
3167 R1.OriginLocationPartyNumber AS OrigLocationID,
3168 ORIG.AirportCode AS OrigAirportCode,
3169 DEST.[Name] AS DestName,
3170 DEST.Address1 AS DestAddress1,
3171 DEST.Address2 AS DestAddress2,
3172 DEST.City AS DestCity,
3173 DEST.State AS DestState,
3174 DEST.Country AS DestCountry,
3175 DEST.PostalCode As DestZip,
3176 R2.DestLocationPartyNumber AS DestLocationID,
3177 DEST.AirportCode AS DestAirportCode
3178 FROM #SummaryCore AS S
3179 INNER JOIN #Row AS R1
3180 ON S.RecordID = R1.RecordID
3181 AND S.OriginStopNumber = R1.OriginStopNumber
3182 LEFT OUTER JOIN NTSR.dbo.DimLocation AS ORIG WITH (NOLOCK)
3183 ON R1.OriginKeyLocationID = ORIG.KeyLocationID
3184 INNER JOIN #Row AS R2
3185 ON S.RecordID = R2.RecordID
3186 AND S.DestStopNumber = R2.DestStopNumber
3187 LEFT OUTER JOIN NTSR.dbo.DimLocation AS DEST WITH (NOLOCK)
3188 ON R2.DestKeyLocationID = DEST.KeyLocationID
3189 WHERE R1.LevelNumber = 2 AND R2.LevelNumber = 2
3190 END
3191
3192 IF @SummarizeOcean = 1
3193 BEGIN
3194 INSERT INTO #CustomerLocation
3195 (
3196 CustomerLocation_RecordID
3197 ,OriginStopNumber
3198 ,DestStopNumber
3199 ,OrigName
3200 ,OrigAddress1
3201 ,OrigAddress2
3202 ,OrigCity
3203 ,OrigState
3204 ,OrigCountry
3205 ,OrigZip
3206 ,OrigLocationID
3207 ,OrigAirportCode
3208 ,DestName
3209 ,DestAddress1
3210 ,DestAddress2
3211 ,DestCity
3212 ,DestState
3213 ,DestCountry
3214 ,DestZip
3215 ,DestLocationID
3216 ,DestAirportCode
3217 )
3218 SELECT
3219 R.RecordID AS CustomerLocation_RecordID,
3220 R.OriginStopNumber AS OriginStopNumber,
3221 R.DestStopNumber AS DestStopNumber,
3222 ORIG.[Name] AS OrigName,
3223 ORIG.Address1 AS OrigAddress1,
3224 ORIG.Address2 AS OrigAddress2,
3225 ORIG.City AS OrigCity,
3226 ORIG.State AS OrigState,
3227 ORIG.Country AS OrigCountry,
3228 ORIG.PostalCode As OrigZip,
3229 R.OriginLocationPartyNumber AS OrigLocationID,
3230 ORIG.AirportCode AS OrigAirportCode,
3231 DEST.[Name] AS DestName,
3232 DEST.Address1 AS DestAddress1,
3233 DEST.Address2 AS DestAddress2,
3234 DEST.City AS DestCity,
3235 DEST.State AS DestState,
3236 DEST.Country AS DestCountry,
3237 DEST.PostalCode As DestZip,
3238 R.DestLocationPartyNumber AS DestLocationID,
3239 DEST.AirportCode AS DestAirportCode
3240 FROM #Row AS R
3241 INNER JOIN COSGroup AS CG WITH (NOLOCK)
3242 ON R.COSGroupID = CG.COSGroupID
3243 AND (R.CHRNumber = CG.PrimaryLoadNumber OR R.SourceTypeID = 7)
3244 INNER JOIN NTSR.dbo.DimLocation AS ORIG WITH (NOLOCK)
3245 ON R.OriginKeyLocationID = ORIG.KeyLocationID
3246 INNER JOIN NTSR.dbo.DimLocation AS DEST WITH (NOLOCK)
3247 ON R.DestKeyLocationID = DEST.KeyLocationID
3248 WHERE R.LevelNumber = 2
3249 END
3250
3251 UPDATE #CustomerLocation SET DestState = ''
3252 WHERE DestCountry = DestState
3253
3254 UPDATE #CustomerLocation SET OrigState = ''
3255 WHERE OrigCountry = OrigState
3256 END
3257
3258 IF @ProcessStopNums = 1
3259 BEGIN
3260 IF @RoutingFeature = 1
3261 BEGIN
3262 INSERT INTO #StopNums(StopNums_RecordID, StopNums)
3263 SELECT
3264 R.RecordID,
3265 (SELECT RTRIM(LocationType) + convert(varchar(10), L.StopNumber + 1) + ', '
3266 FROM COLocation AS L WITH (NOLOCK)
3267 WHERE L.COSDetailID = R.COSDetailID
3268 ORDER BY L.StopNumber
3269 FOR XML PATH('')) AS StopNums
3270 FROM #Row AS R WHERE COSGroupID = -1 -- no INTL
3271 END
3272 ELSE
3273 BEGIN
3274 ;WITH StopTypes(StopType) AS
3275 (
3276 SELECT 'P' UNION ALL
3277 SELECT 'D'
3278 )
3279
3280 INSERT INTO #StopNums(StopNums_RecordID, StopNums)
3281 SELECT
3282 R.RecordID,
3283 (SELECT RTRIM(LocationType) + convert(varchar(10), L.StopNumber + 1) + ', '
3284 FROM COLocation AS L WITH (NOLOCK)
3285 INNER JOIN StopTypes AS S
3286 ON S.StopType = L.LocationType
3287 WHERE L.COSDetailID = R.COSDetailID
3288 ORDER BY L.StopNumber
3289 FOR XML PATH('')) AS StopNums
3290 FROM #Row AS R WHERE COSGroupID = -1 -- no INTL
3291 END
3292 END
3293
3294 -- OK02082008=============================================================================================
3295 -- Load #MISC
3296 -- =======================================================================================================
3297
3298 --PRINT 'Load Misc'
3299
3300 IF @ProcessMisc = 1
3301 BEGIN
3302 CREATE TABLE #MiscTemp
3303 (
3304 RecordID INT,
3305 IntlCHRRole VARCHAR(1),
3306 [Name] VARCHAR(255),
3307 ExternalRoleName VARCHAR(20),
3308 DeleteFlg BIT
3309 )
3310
3311 CREATE TABLE #COrderRoles ([Role] VARCHAR(20), [ExternalRoleName] VARCHAR(20))
3312 CREATE TABLE #COServiceRoles ([Role] VARCHAR(20), [ExternalRoleName] VARCHAR(20))
3313 CREATE TABLE #COSDetailRoles ([Role] VARCHAR(20), [ExternalRoleName] VARCHAR(20))
3314
3315 INSERT INTO #COrderRoles([Role], [ExternalRoleName])
3316 (
3317 SELECT 'SHIPPER', 'ShipperName' UNION ALL
3318 SELECT 'CONSIGNEE', 'ConsigneeName' UNION ALL
3319 SELECT 'VENDOR', 'VendorName' UNION ALL
3320 SELECT 'IMPORTEROFRECORD', 'ImporterOfRecord' UNION ALL
3321 SELECT 'MLH', 'MasterLinehaulName' UNION ALL
3322 SELECT 'ENTERED', 'EnteredBy'
3323 )
3324
3325 INSERT INTO #COServiceRoles([Role], [ExternalRoleName])
3326 (
3327 SELECT 'BUYER', 'Buyer'
3328 )
3329
3330 INSERT INTO #COSDetailRoles([Role], [ExternalRoleName])
3331 (
3332 SELECT 'CUSTOMER','CustomerName' UNION ALL
3333 SELECT 'CUSTENTERED', 'OrderedBy' -- ORDERED BY : Bill said to use from LoadCustomers.OrderedBy
3334 )
3335
3336 -- Insert summary records
3337 INSERT INTO #MiscTemp(RecordID, IntlCHRRole, [Name], ExternalRoleName)
3338 SELECT DISTINCT
3339 X.RecordID,
3340 X.IntlCHRRole,
3341 X.[Name],
3342 X.ExternalRoleName
3343 FROM
3344
3345 (SELECT DISTINCT
3346 R.RecordID,
3347 R.IntlCHRRole,
3348 OP.[Name],
3349 OPR.ExternalRoleName
3350 FROM #Row AS R
3351 INNER JOIN COService AS S WITH(NOLOCK)
3352 ON R.COServiceID = S.COServiceID
3353 INNER JOIN COrderParty AS COP WITH(NOLOCK)
3354 ON S.COrderID = COP.COrderID
3355 INNER JOIN OrderParty AS OP WITH(NOLOCK)
3356 ON COP.OrderPartyID = OP.OrderPartyID
3357 INNER JOIN #COrderRoles AS OPR
3358 ON OP.[Role] = OPR.[Role]
3359
3360 UNION
3361
3362 SELECT DISTINCT
3363 R.RecordID,
3364 R.IntlCHRRole,
3365 OP.[Name],
3366 OPR.ExternalRoleName
3367 FROM #Row AS R
3368 INNER JOIN COSGroup G (NOLOCK)
3369 ON G.COSGroupID = R.COSGroupID
3370 INNER JOIN COService AS S WITH(NOLOCK)
3371 ON S.COSGroupID = G.COSGroupID
3372 AND ((ISNULL(G.PrimaryLoadNumber, -1) > 0 AND S.FirstLoadNumber = G.PrimaryLoadNumber)
3373 OR
3374 ( ISNULL(G.PrimaryCustomerOrderNumber, -1) > 0 AND S.CustomerOrderNumber = G.PrimaryCustomerOrderNumber))
3375 INNER JOIN COrderParty AS COP WITH(NOLOCK)
3376 ON S.COrderID = COP.COrderID
3377 INNER JOIN OrderParty AS OP WITH(NOLOCK)
3378 ON COP.OrderPartyID = OP.OrderPartyID
3379 INNER JOIN #COrderRoles AS OPR
3380 ON OP.[Role] = OPR.[Role]) AS X
3381
3382 UNION ALL
3383
3384 SELECT DISTINCT
3385 R.RecordID, R.IntlCHRRole, OP.[Name], OPR.ExternalRoleName
3386 FROM #Row AS R
3387
3388 INNER JOIN COServiceParty AS P WITH(NOLOCK)
3389 ON R.COServiceID = P.COServiceID
3390 INNER JOIN OrderParty AS OP WITH(NOLOCK)
3391 ON P.OrderPartyID = OP.OrderPartyID
3392 INNER JOIN #COServiceRoles AS OPR
3393 ON OP.[Role] = OPR.[Role]
3394
3395 UNION ALL
3396
3397 SELECT DISTINCT
3398 R.RecordID, R.IntlCHRRole, OP.[Name], OPR.ExternalRoleName
3399 FROM #Row AS R
3400 INNER JOIN COSDetailParty AS P WITH(NOLOCK)
3401 ON R.COSDetailID = P.COSDetailID
3402 INNER JOIN OrderParty AS OP WITH(NOLOCK)
3403 ON P.OrderPartyID = OP.OrderPartyID
3404 INNER JOIN #COSDetailRoles AS OPR
3405 ON OP.[Role] = OPR.[Role]
3406
3407 UPDATE MT SET DeleteFlg = 1
3408 FROM #MiscTemp AS MT
3409 WHERE EXISTS (SELECT 1 FROM #MiscTemp AS MT2
3410 WHERE MT.RecordID = MT2.RecordID AND MT.ExternalRoleName = MT2.ExternalRoleName
3411 GROUP BY MT2.RecordID, MT2.ExternalRoleName
3412 HAVING COUNT(1) > 1)
3413
3414 INSERT INTO #MiscTemp(RecordID, IntlCHRRole, [Name], ExternalRoleName)
3415 SELECT DISTINCT
3416 MT.RecordID,
3417 MT.IntlCHRRole,
3418 SUBSTRING((
3419 SELECT MT2.[Name] + ', '
3420 FROM #MiscTemp AS MT2
3421 WHERE
3422 MT.RecordID = MT2.RecordID
3423 AND MT.ExternalRoleName = MT2.ExternalRoleName
3424 GROUP BY MT2.[Name]
3425 FOR XML PATH('')
3426 ), 1,255) AS [Name],
3427
3428 MT.ExternalRoleName
3429 FROM #MiscTemp AS MT
3430 WHERE MT.DeleteFlg = 1
3431
3432 DELETE FROM #MiscTemp WHERE DeleteFlg =1
3433
3434 INSERT INTO [#MISC]
3435 (
3436 MISC_RecordID,
3437 CustomerName,
3438 ShipperName,
3439 ConsigneeName,
3440 VendorName,
3441 ImporterOfRecord,
3442 Buyer,
3443 OrderedBy,
3444 EnteredBy,
3445 MasterLinehaulName
3446 )
3447
3448 SELECT
3449 P.RecordID,
3450 ISNULL(P.[CustomerName], ''),
3451 ISNULL(P.[ShipperName], ''),
3452 ISNULL(P.[ConsigneeName], ''),
3453 ISNULL(P.[VendorName], ''),
3454 ISNULL(P.[ImporterOfRecord], ''),
3455 ISNULL(P.[Buyer], ''),
3456 ISNULL(P.[OrderedBy], ''),
3457 ISNULL(P.[EnteredBy], ''),
3458 CASE
3459 WHEN IntlCHRRole = 'N' THEN 'Christal Lines'
3460 ELSE ISNULL(P.[MasterLinehaulName], '')
3461 END AS MasterLinehaulName
3462 FROM
3463 (
3464 SELECT RecordID, IntlCHRRole, [Name], ExternalRoleName
3465 FROM [#MiscTemp]
3466
3467 ) AS UP
3468
3469 PIVOT
3470 (
3471 MAX([Name])
3472 FOR ExternalRoleName IN
3473 (
3474 [CustomerName],
3475 [ShipperName],
3476 [ConsigneeName],
3477 [VendorName],
3478 [ImporterOfRecord],
3479 [Buyer],
3480 [OrderedBy],
3481 [EnteredBy],
3482 [MasterLinehaulName]
3483 )
3484 ) AS P
3485
3486 END
3487
3488 -- OK02082008=============================================================================================
3489 -- Load #MiscDate
3490 -- =======================================================================================================
3491
3492 --PRINT 'Load MiscDate'
3493
3494 IF @ProcessMiscDates = 1
3495 BEGIN
3496 ;WITH COSDateTypeMin(DateType) AS
3497 (
3498 SELECT 'Close Date' UNION ALL
3499 SELECT 'Truckload Activity Date' UNION ALL
3500 SELECT 'Delivery Order Created Date' UNION ALL
3501 SELECT 'Document Tracking Date' UNION ALL
3502SELECT 'Ready By Date' UNION ALL
3503 SELECT 'Deliver By Date'
3504 )
3505
3506 INSERT INTO [#MiscDate]
3507 (
3508 MiscDate_RecordID,
3509 CloseDate,
3510 DocumentTrackingDate,
3511 DeliveryOrderCreatedDate,
3512 TruckloadActivityDate,
3513 EstimatedPickupDate,
3514 EstimatedDeliveryDate
3515 )
3516
3517 -- Fixes the null aggregate issue : smalldatetime ranges are 1900 to 2079
3518 -- The double ISNULL/NULLIF checks are needed (in this select statement
3519 -- and in the subquery) because SQL is not smart enough to figure it out.
3520 SELECT
3521 P.RecordID,
3522 NULLIF(MAX(ISNULL([Close Date], 99990101)), 99990101) AS CloseDate,
3523 NULLIF(MIN(ISNULL([Document Tracking Date], 99990101)), 99990101) AS DocumentTrackingDate,
3524 NULLIF(MIN(ISNULL([Delivery Order Created Date], 99990101)), 99990101) AS DeliveryOrderCreatedDate,
3525 NULLIF(MIN(ISNULL([Truckload Activity Date], 99990101)), 99990101) AS TruckloadActivityDate,
3526 NULLIF(MIN(ISNULL([Ready By Date], 99990101)), 99990101) AS EstimatedPickupDate,
3527 NULLIF(MAX(ISNULL([Deliver By Date], 99990101)), 99990101) AS EstimatedDeliveryDate
3528 FROM
3529 (
3530 SELECT
3531 R.RecordID,
3532 D.DateType,
3533 -- We can't add the NULLIF here because we do a
3534 -- MIN again in PIVOT
3535 MIN(ISNULL(D.DateValue, 99990101)) AS DateValue
3536 FROM #Row AS R
3537 INNER JOIN COServiceDate AS D WITH(NOLOCK)
3538 ON R.COServiceID = D.COServiceID
3539 INNER JOIN COSDateTypeMin AS DT WITH(NOLOCK)
3540 ON D.DateType = DT.DateType
3541 GROUP BY R.RecordID, D.DateType
3542 ) AS UP(RecordID, DateType, DateValue)
3543
3544 PIVOT
3545 (
3546 MIN(DateValue)
3547 FOR DateType IN
3548 (
3549 [Close Date],
3550 [Document Tracking Date],
3551 [Delivery Order Created Date],
3552 [Truckload Activity Date],
3553 [Ready By Date],
3554 [Deliver By Date]
3555 )
3556 ) AS P
3557
3558 GROUP BY P.RecordID
3559
3560 INSERT INTO #MiscDate
3561 (
3562 MiscDate_RecordID,
3563 EstimatedPickupDate,
3564 Overwrite
3565 )
3566 SELECT
3567 R.RecordID,
3568 MIN(PickETA.DateValue),
3569 1
3570 FROM #Row AS R
3571 INNER JOIN COLocationDate AS PickETA WITH (NOLOCK)
3572 ON R.OriginCOLocationID = PickETA.COLocationID
3573 AND PickETA.DateType = 'Pick ETA'
3574 WHERE R.COSGroupID > -1 AND PickETA.DateValue IS NOT NULL
3575 GROUP BY R.RecordID
3576
3577 INSERT INTO #MiscDate
3578 (
3579 MiscDate_RecordID,
3580 EstimatedDeliveryDate,
3581 Overwrite
3582 )
3583 SELECT
3584 R.RecordID,
3585 MAX(DropETA.DateValue),
3586 1
3587 FROM #Row AS R
3588 INNER JOIN COLocationDate AS DropETA WITH (NOLOCK)
3589 ON R.DestCOLocationID = DropETA.COLocationID
3590 AND DropETA.DateType = 'Drop ETA'
3591 WHERE R.COSGroupID > -1
3592 GROUP BY R.RecordID
3593
3594 UPDATE M SET
3595 EstimatedPickupDate = M2.EstimatedPickupDate
3596 FROM #MiscDate AS M
3597 INNER JOIN #MiscDate AS M2
3598 ON M.MiscDate_RecordID = M2.MiscDate_RecordID
3599 WHERE M.Overwrite IS NULL AND M2.OverWrite = 1 AND M2.EstimatedPickupDate IS NOT NULL
3600
3601 UPDATE M SET
3602 EstimatedDeliveryDate = M2.EstimatedDeliveryDate
3603 FROM #MiscDate AS M
3604 INNER JOIN #MiscDate AS M2
3605 ON M.MiscDate_RecordID = M2.MiscDate_RecordID
3606 WHERE M.Overwrite IS NULL AND M2.OverWrite = 1 AND M2.EstimatedDeliveryDate IS NOT NULL
3607
3608 DELETE FROM #MiscDate WHERE Overwrite = 1
3609 END
3610
3611 -- OK02062008=============================================================================================
3612 -- Load #InterLocation
3613 -- =======================================================================================================
3614
3615 --PRINT 'Load InterLocation'
3616
3617 -- 04/01/2008 GANASAD Added pick port and drop ports
3618 -- Assumption: All parts of summarized shipments will
3619 -- have same intermediate stops. Example all multi-
3620 -- container loads will go through same ports.
3621 IF @ProcessInterLocations = 1 OR @ProcessLFUDates = 1
3622 BEGIN
3623 CREATE TABLE #InterLocationType
3624 (
3625 LocationType CHAR(2),
3626 LocationStyle CHAR(1),
3627 MinFlg BIT
3628 )
3629
3630 INSERT INTO #InterLocationType(LocationType, LocationStyle, MinFlg)
3631 SELECT 'OT', NULL, 1 UNION ALL
3632 SELECT 'OR', NULL, 1 UNION ALL
3633 SELECT 'OP', NULL, 1 UNION ALL
3634 SELECT 'DT', NULL, 0 UNION ALL
3635 SELECT 'DR', NULL, 0 UNION ALL
3636 SELECT 'DP', NULL, 0 UNION ALL
3637 SELECT 'P', 'P', 1 UNION ALL -- Pick Port
3638 SELECT 'D', 'P', 0 UNION ALL -- Drop Port
3639 SELECT 'OA', NULL, 1 UNION ALL -- Origin Airport 04/17/2008 GANASAD
3640 SELECT 'DA', NULL, 0 UNION ALL -- Destination Airport 04/17/2008 GANASAD
3641 SELECT 'P', 'A', 1 UNION ALL -- Pick Airport 4/18/2008 GANASAD
3642 SELECT 'D', 'A', 0 -- Drop Airport 4/18/2008 GANASAD
3643
3644 CREATE TABLE #InterLocationUP(
3645 RecordID INT,
3646 StopNumber INT,
3647 [Name] NVARCHAR(200),
3648 CityCountry VARCHAR(50),
3649 LocationType CHAR(2)
3650 )
3651
3652 INSERT INTO #InterLocationUP (RecordID, StopNumber, Name, CityCountry, LocationType)
3653 SELECT DISTINCT
3654 R.InterLocation_RecordID AS InterLocation_RecordID,
3655 R.StopNumber AS StopNumber,
3656 DL.[Name] AS Name,
3657 CASE
3658 WHEN R.LocationType IN
3659 (
3660 'P',
3661 'D',
3662 'DP',
3663 'OP',
3664 'OA',
3665 'DA'
3666 )
3667 THEN DL.Country
3668 ELSE DL.City
3669 END AS CityCountry,
3670 R.LocationType AS LocationType
3671 FROM (
3672 SELECT R1.RecordID AS InterLocation_RecordID,
3673 MIN(L.StopNumber) AS StopNumber,
3674 L.LocationType AS LocationType,
3675 L.COSDetailID AS COSDetailID
3676 FROM #Row AS R1
3677INNER JOIN COLocation AS L WITH(NOLOCK)
3678 ON R1.COSDetailID = L.COSDetailID
3679 INNER JOIN #InterLocationType AS LTP
3680 ON
3681 L.LocationType = LTP.LocationType
3682 AND ISNULL(LTP.LocationStyle, L.LocationStyle) = L.LocationStyle
3683 WHERE R1.DisplayServiceFlg=1 AND LTP.MinFlg=1
3684 GROUP BY R1.RecordID,L.COSDetailID,L.LocationType
3685
3686 UNION ALL
3687
3688 SELECT R1.RecordID AS InterLocation_RecordID,
3689MAX(L.StopNumber) AS StopNumber,
3690 L.LocationType AS LocationType,
3691 L.COSDetailID AS COSDetailID
3692 FROM #Row AS R1
3693 INNER JOIN COLocation AS L WITH(NOLOCK)
3694 ON R1.COSDetailID = L.COSDetailID
3695 INNER JOIN #InterLocationType AS LTP
3696 ON
3697 L.LocationType = LTP.LocationType
3698 AND ISNULL(LTP.LocationStyle, L.LocationStyle) = L.LocationStyle
3699 WHERE R1.DisplayServiceFlg=1 AND LTP.MinFlg=0
3700 GROUP BY R1.RecordID,L.COSDetailID,L.LocationType
3701 ) AS R
3702 INNER JOIN COLocation AS L WITH(NOLOCK)
3703 ON R.COSDetailID = L.COSDetailID
3704 AND R.StopNumber = L.[StopNumber]
3705 INNER JOIN NTSR.dbo.DimLocation AS DL WITH(NOLOCK)
3706 ON L.KeyLocationID = DL.KeyLocationID
3707
3708 INSERT INTO #InterLocation
3709 (
3710 InterLocation_RecordID
3711 ,OrigTerminalStopNumber
3712 ,OrigTerminalName
3713 ,OrigTerminalCity
3714 ,OrigRampStopNumber
3715,OrigRampName
3716 ,OrigRampCity
3717 ,LoadingPortStopNumber
3718 ,LoadingPort
3719 ,LoadingPortCountry
3720 ,DischargePortStopNumber
3721 ,DischargePort
3722 ,DischargePortCountry
3723 ,DestRampStopNumber
3724 ,DestRampName
3725 ,DestRampCity
3726 ,DestTerminalStopNumber
3727 ,DestTerminalName
3728 ,DestTerminalCity
3729 )
3730
3731 SELECT DISTINCT
3732 R.RecordID AS InterLocation_RecordID,
3733 L_OT.StopNumber AS OrigTerminalStopNumber,
3734 L_OT.[Name] AS OrigTerminalName,
3735 L_OT.CityCountry AS OrigTerminalCity,
3736
3737 L_OR.StopNumber AS OrigRampStopNumber,
3738 L_OR.[Name] AS OrigRampName,
3739 L_OR.CityCountry AS OrigRampCity,
3740
3741 ISNULL(ISNULL(L_OP.StopNumber, L_P.StopNumber), L_OA.StopNumber) AS LoadingPortStopNumber,
3742 ISNULL(ISNULL(L_OP.[Name],L_P.[Name]), L_OA.[Name]) AS LoadingPort,
3743 ISNULL(ISNULL(L_OP.CityCountry,L_P.CityCountry), L_OA.CityCountry) AS LoadingPortCountry,
3744
3745 ISNULL(ISNULL(L_DP.StopNumber,L_D.StopNumber), L_DA.StopNumber) AS DischargePortStopNumber,
3746 ISNULL(ISNULL(L_DP.[Name],L_D.[Name]), L_DA.[Name]) AS DischargePort,
3747 ISNULL(ISNULL(L_DP.CityCountry,L_D.CityCountry), L_DA.CityCountry) AS DischargePortCountry,
3748
3749 L_DR.StopNumber AS DestRampStopNumber,
3750 L_DR.[Name] AS DestRampName,
3751 L_DR.CityCountry AS DestRampCity,
3752
3753 L_DT.StopNumber AS DestTerminalStopNumber,
3754 L_DT.[Name] AS DestTerminalName,
3755 L_DT.CityCountry AS DestTerminalCity
3756
3757 FROM #InterLocationUP AS R
3758
3759 LEFT OUTER JOIN #InterLocationUP AS L_OT
3760 ON R.RecordID = L_OT.RecordID AND L_OT.LocationType = 'OT'
3761
3762 LEFT OUTER JOIN #InterLocationUP AS L_OR
3763 ON R.RecordID = L_OR.RecordID AND L_OR.LocationType = 'OR'
3764
3765 LEFT OUTER JOIN #InterLocationUP AS L_OP
3766 ON R.RecordID = L_OP.RecordID AND L_OP.LocationType = 'OP'
3767
3768 LEFT OUTER JOIN #InterLocationUP AS L_P
3769 ON R.RecordID = L_P.RecordID AND L_P.LocationType = 'P' -- Pick Port
3770
3771 LEFT OUTER JOIN #InterLocationUP AS L_DP
3772 ON R.RecordID = L_DP.RecordID AND L_DP.LocationType = 'DP'
3773
3774 LEFT OUTER JOIN #InterLocationUP AS L_D
3775 ON R.RecordID = L_D.RecordID AND L_D.LocationType = 'D' -- Drop Port
3776
3777 LEFT OUTER JOIN #InterLocationUP AS L_DR
3778 ON R.RecordID = L_DR.RecordID AND L_DR.LocationType = 'DR'
3779
3780 LEFT OUTER JOIN #InterLocationUP AS L_DT
3781 ON R.RecordID = L_DT.RecordID AND L_DT.LocationType = 'DT'
3782
3783 LEFT OUTER JOIN #InterLocationUP AS L_OA -- Origin Airport 03/17/2008 GANASAD
3784 ON R.RecordID = L_OA.RecordID AND L_OA.LocationType = 'OA'
3785
3786 LEFT OUTER JOIN #InterLocationUP AS L_DA -- Destination Airport 03/17/2008 GANASAD
3787 ON R.RecordID = L_DA.RecordID AND L_DA.LocationType = 'DA'
3788 END
3789
3790 -- OK02062008=============================================================================================
3791 -- Load #FUDate
3792 -- =======================================================================================================
3793
3794 --PRINT 'Load FUDate'
3795
3796 IF @ProcessFUDates = 1
3797 BEGIN
3798 INSERT INTO #UnpivotedFUDate
3799 (
3800 RecordID,
3801 DateTimeType,
3802 DateTimeValue
3803 )
3804 SELECT R.RecordID, CSD.DateTimeType, MIN(CSD.DateTimeValue) AS DateTimeValue
3805 FROM #Row AS R
3806 INNER JOIN #UnpivotedCOServiceDates AS CSD
3807 ON R.COServiceID = CSD.COServiceID
3808 GROUP BY R.RecordID, CSD.DateTimeType
3809
3810;WITH PickCOFUDateTypes(DateTimeType) AS
3811 (
3812 SELECT 'Earliest Requested Pickup Date' UNION ALL
3813 SELECT 'Earliest Requested Pickup Time' UNION ALL
3814 SELECT 'Latest Requested Pickup Date' UNION ALL
3815 SELECT 'Latest Requested Pickup Time'
3816 )
3817 INSERT INTO #UnpivotedFUDate
3818 (
3819 RecordID,
3820 DateTimeType,
3821 DateTimeValue
3822 )
3823 SELECT R.RecordID, LD.DateTimeType, MIN(LD.DateTimeValue) AS DateTimeValue
3824 FROM #Row AS R
3825
3826 INNER JOIN COLocation AS L WITH(NOLOCK)
3827 ON R.COSDetailID = L.COSDetailID AND L.StopNumber = R.OriginStopNumber AND L.COLocationID = R.OriginCOLocationID
3828 INNER JOIN [#UnpivotedCOLocationDates] AS LD
3829 ON L.COLocationID = LD.COLocationID
3830 INNER JOIN PickCOFUDateTypes AS P WITH(NOLOCK)
3831 ON LD.DateTimeType = P.DateTimeType
3832 GROUP BY R.RecordID, LD.DateTimeType
3833
3834;WITH PickFUDateTypes(DateTimeType) AS
3835 (
3836 SELECT 'Earliest Scheduled Pickup Date' UNION ALL
3837 SELECT 'Earliest Scheduled Pickup Time' UNION ALL
3838 SELECT 'Latest Scheduled Pickup Date' UNION ALL
3839 SELECT 'Latest Scheduled Pickup Time' UNION ALL
3840
3841 SELECT 'Arrival Pickup Date' UNION ALL
3842 SELECT 'Arrival Pickup Time' UNION ALL
3843 SELECT 'Latest Actual Pickup Date' UNION ALL
3844 SELECT 'Latest Actual Pickup Time' UNION ALL
3845 SELECT 'Drop Trailer Arrival Date Shipper' UNION ALL
3846 SELECT 'Drop Trailer Arrival Time Shipper' UNION ALL
3847
3848 SELECT 'Drop Trailer Ready Date Shipper' UNION ALL
3849 SELECT 'Drop Trailer Ready Time Shipper' UNION ALL
3850
3851 SELECT 'Earliest Requested Pickup Date' UNION ALL
3852 SELECT 'Earliest Requested Pickup Time' UNION ALL
3853 SELECT 'Latest Requested Pickup Date' UNION ALL
3854 SELECT 'Latest Requested Pickup Time'
3855 )
3856 INSERT INTO #UnpivotedFUDate
3857 (
3858 RecordID,
3859 DateTimeType,
3860 DateTimeValue
3861 )
3862 SELECT R.RecordID, SD.DateTimeType, MIN(SD.DateTimeValue) AS DateTimeValue
3863 FROM #Row AS R
3864 INNER JOIN #SPODetailID S (NOLOCK) ON S.COSDetailID = R.COSDetailID
3865 INNER JOIN SPODLocation AS SL WITH(NOLOCK) ON SL.SPODetailID = S.SPODetailID
3866 INNER JOIN [#UnpivotedSPODLocationDates] SD
3867 ON SL.SPODLocationID = SD.SPODLocationID AND SD.KeyLocationID = R.OriginSPODKeyLocationID
3868 INNER JOIN PickFUDateTypes AS PFU WITH(NOLOCK)
3869 ON SD.DateTimeType = PFU.DateTimeType
3870 WHERE NOT EXISTS(SELECT Top 1 * FROM #UnpivotedFUDate UFD (NOLOCK) WHERE UFD.DateTimeType = SD.DateTimeType AND UFD.RecordID = R.RecordID)
3871 GROUP BY R.RecordID, SD.DateTimeType
3872
3873;WITH DropCOFUDateTypes (DateTimeType) AS
3874 (
3875 SELECT 'Earliest Requested Delivery Date' UNION ALL
3876 SELECT 'Earliest Requested Delivery Time' UNION ALL
3877 SELECT 'Latest Requested Delivery Date' UNION ALL
3878 SELECT 'Latest Requested Delivery Time'
3879 )
3880INSERT INTO #UnpivotedFUDate
3881 (
3882 RecordID,
3883 DateTimeType,
3884 DateTimeValue
3885 )
3886 SELECT R.RecordID, LD.DateTimeType, MAX(LD.DateTimeValue) AS DateTimeValue
3887 FROM #Row AS R
3888
3889 INNER JOIN COLocation AS L WITH(NOLOCK)
3890 ON R.COSDetailID = L.COSDetailID AND L.StopNumber = R.DestStopNumber AND L.COLocationID = R.DestCOLocationID
3891 INNER JOIN [#UnpivotedCOLocationDates] AS LD
3892 ON L.COLocationID = LD.COLocationID
3893 INNER JOIN DropCOFUDateTypes AS DFU WITH(NOLOCK)
3894 ON LD.DateTimeType = DFU.DateTimeType
3895 GROUP BY R.RecordID, LD.DateTimeType
3896
3897;WITH DropFUDateTypes (DateTimeType) AS
3898 (
3899 SELECT 'Earliest Scheduled Delivery Date' UNION ALL
3900 SELECT 'Earliest Scheduled Delivery Time' UNION ALL
3901 SELECT 'Latest Scheduled Delivery Date' UNION ALL
3902 SELECT 'Latest Scheduled Delivery Time' UNION ALL
3903
3904 SELECT 'Arrival Delivery Date' UNION ALL
3905 SELECT 'Arrival Delivery Time' UNION ALL
3906 SELECT 'Latest Actual Delivery Date' UNION ALL
3907 SELECT 'Latest Actual Delivery Time' UNION ALL
3908 SELECT 'Drop Trailer Arrival Date Consignee' UNION ALL
3909 SELECT 'Drop Trailer Arrival Time Consignee' UNION ALL
3910
3911 SELECT 'Drop Trailer Ready Date Consignee' UNION ALL
3912 SELECT 'Drop Trailer Ready Time Consignee' UNION ALL
3913
3914 SELECT 'Earliest Requested Delivery Date' UNION ALL
3915 SELECT 'Earliest Requested Delivery Time' UNION ALL
3916 SELECT 'Latest Requested Delivery Date' UNION ALL
3917 SELECT 'Latest Requested Delivery Time'
3918 )
3919 INSERT INTO #UnpivotedFUDate
3920 (
3921 RecordID,
3922 DateTimeType,
3923 DateTimeValue
3924 )
3925 SELECT R.RecordID, SD.DateTimeType, MAX(SD.DateTimeValue) AS DateTimeValue
3926 FROM #Row AS R
3927 INNER JOIN #SPODetailID S (NOLOCK) ON S.COSDetailID = R.COSDetailID
3928 INNER JOIN SPODLocation AS SL WITH(NOLOCK) ON SL.SPODetailID = S.SPODetailID
3929 INNER JOIN [#UnpivotedSPODLocationDates] SD
3930 ON SL.SPODLocationID = SD.SPODLocationID AND SD.KeyLocationID = R.DestSPODKeyLocationID
3931 INNER JOIN DropFUDateTypes AS DFU WITH(NOLOCK)
3932 ON SD.DateTimeType = DFU.DateTimeType
3933 WHERE NOT EXISTS(SELECT Top 1 * FROM #UnpivotedFUDate UFD (NOLOCK) WHERE UFD.DateTimeType = SD.DateTimeType AND UFD.RecordID = R.RecordID)
3934 GROUP BY R.RecordID, SD.DateTimeType
3935
3936 INSERT INTO #FUDate
3937 (
3938 FUDate_RecordID
3939 ,EnterDate
3940 ,EnterTime
3941
3942 ,EarliestReqPickupDate
3943 ,EarliestReqPickupTime
3944 ,EarliestReqDeliveryDate
3945 ,EarliestReqDeliveryTime
3946
3947 ,LatestReqPickupDate
3948 ,LatestReqPickupTime
3949 ,LatestReqDeliveryDate
3950 ,LatestReqDeliveryTime
3951
3952 ,EarliestSchedPickupDate
3953 ,EarliestSchedPickupTime
3954 ,EarliestSchedDeliveryDate
3955 ,EarliestSchedDeliveryTime
3956
3957 ,LatestSchedPickupDate
3958 ,LatestSchedPickupTime
3959 ,LatestSchedDeliveryDate
3960 ,LatestSchedDeliveryTime
3961
3962 ,EarliestActualPickupDate
3963 ,EarliestActualPickupTime
3964 ,EarliestActualDeliveryDate
3965 ,EarliestActualDeliveryTime
3966
3967 ,LatestActualPickupDate
3968 ,LatestActualPickupTime
3969 ,LatestActualDeliveryDate
3970 ,LatestActualDeliveryTime
3971
3972 ,ShipperDropTrailerArrivalDate
3973 ,ShipperDropTrailerArrivalTime
3974 ,ConsigneeDropTrailerArrivalDate
3975 ,ConsigneeDropTrailerArrivalTime
3976
3977 ,ShipperDropTrailerReadyDate
3978 ,ShipperDropTrailerReadyTime
3979 ,ConsigneeDropTrailerReadyDate
3980 ,ConsigneeDropTrailerReadyTime
3981 )
3982
3983 SELECT
3984 P.RecordID,
3985 [Enter Date],
3986 [Enter Time],
3987
3988 [Earliest Requested Pickup Date],
3989 [Earliest Requested Pickup Time],
3990 [Earliest Requested Delivery Date],
3991 [Earliest Requested Delivery Time],
3992
3993 [Latest Requested Pickup Date],
3994 [Latest Requested Pickup Time],
3995 [Latest Requested Delivery Date],
3996 [Latest Requested Delivery Time],
3997
3998 [Earliest Scheduled Pickup Date],
3999 [Earliest Scheduled Pickup Time],
4000 [Earliest Scheduled Delivery Date],
4001 [Earliest Scheduled Delivery Time],
4002
4003 [Latest Scheduled Pickup Date],
4004 [Latest Scheduled Pickup Time],
4005 [Latest Scheduled Delivery Date],
4006 [Latest Scheduled Delivery Time],
4007
4008 [Arrival Pickup Date],
4009 [Arrival Pickup Time],
4010 [Arrival Delivery Date],
4011 [Arrival Delivery Time],
4012
4013 [Latest Actual Pickup Date],
4014 [Latest Actual Pickup Time],
4015 [Latest Actual Delivery Date],
4016 [Latest Actual Delivery Time],
4017
4018 [Drop Trailer Arrival Date Shipper],
4019 [Drop Trailer Arrival Time Shipper],
4020 [Drop Trailer Arrival Date Consignee],
4021 [Drop Trailer Arrival Time Consignee],
4022
4023 [Drop Trailer Ready Date Shipper],
4024 [Drop Trailer Ready Time Shipper],
4025 [Drop Trailer Ready Date Consignee],
4026 [Drop Trailer Ready Time Consignee]
4027 FROM
4028 (
4029 SELECT RecordID, DateTimeType, DateTimeValue
4030 FROM #UnpivotedFUDate UFD (NOLOCK)
4031 ) AS UP
4032
4033 PIVOT
4034 (
4035 MIN(UP.DateTimeValue) FOR UP.DateTimeType IN
4036 (
4037 [Enter Date],
4038 [Enter Time],
4039
4040 [Earliest Requested Pickup Date],
4041 [Earliest Requested Pickup Time],
4042 [Earliest Requested Delivery Date],
4043 [Earliest Requested Delivery Time],
4044
4045 [Latest Requested Pickup Date],
4046 [Latest Requested Pickup Time],
4047 [Latest Requested Delivery Date],
4048 [Latest Requested Delivery Time],
4049
4050 [Earliest Scheduled Pickup Date],
4051 [Earliest Scheduled Pickup Time],
4052 [Earliest Scheduled Delivery Date],
4053 [Earliest Scheduled Delivery Time],
4054
4055 [Latest Scheduled Pickup Date],
4056 [Latest Scheduled Pickup Time],
4057 [Latest Scheduled Delivery Date],
4058 [Latest Scheduled Delivery Time],
4059
4060 [Arrival Pickup Date],
4061 [Arrival Pickup Time],
4062 [Arrival Delivery Date],
4063 [Arrival Delivery Time],
4064
4065 [Latest Actual Pickup Date],
4066 [Latest Actual Pickup Time],
4067 [Latest Actual Delivery Date],
4068 [Latest Actual Delivery Time],
4069
4070 [Drop Trailer Arrival Date Shipper],
4071 [Drop Trailer Arrival Time Shipper],
4072 [Drop Trailer Arrival Date Consignee],
4073 [Drop Trailer Arrival Time Consignee],
4074
4075 [Drop Trailer Ready Date Shipper],
4076 [Drop Trailer Ready Time Shipper],
4077 [Drop Trailer Ready Date Consignee],
4078 [Drop Trailer Ready Time Consignee]
4079 )
4080 ) AS p
4081 END
4082
4083 -- OK02082008=============================================================================================
4084 -- Load #LFUDate
4085 -- =============================================================================================
4086
4087 --PRINT 'Load LFUDate'
4088
4089 IF @ProcessLFUDates = 1
4090 BEGIN
4091
4092 CREATE TABLE #ILStopNumbers
4093 (
4094 RecordID INT,
4095 StopNumber INT,
4096 LocationType CHAR(2)
4097 )
4098
4099 INSERT INTO #ILStopNumbers (RecordID,StopNumber,LocationType)
4100 SELECT
4101 UP.InterLocation_RecordID,
4102 UP.StopNumber,
4103 CASE StopNumberType
4104 WHEN 'OrigTerminalStopNumber' THEN 'OT'
4105 WHEN 'OrigRampStopNumber' THEN 'OR'
4106 WHEN 'LoadingPortStopNumber' THEN 'OP'
4107 WHEN 'DischargePortStopNumber' THEN 'DP'
4108 WHEN 'DestRampStopNumber' THEN 'DR'
4109 WHEN 'DestTerminalStopNumber' THEN 'DT'
4110 END AS LocationType
4111 FROM
4112 (
4113 SELECT
4114 IL.InterLocation_RecordID,
4115 IL.DestRampStopNumber,
4116 IL.DestTerminalStopNumber,
4117 IL.DischargePortStopNumber,
4118 IL.LoadingPortStopNumber,
4119IL.OrigRampStopNumber,
4120 IL.OrigTerminalStopNumber
4121 FROM #InterLocation AS IL
4122 ) AS P
4123
4124 UNPIVOT
4125 (
4126 StopNumber FOR StopNumberType IN
4127 (
4128 P.DestRampStopNumber,
4129 P.DestTerminalStopNumber,
4130 P.DischargePortStopNumber,
4131 P.LoadingPortStopNumber,
4132 P.OrigRampStopNumber,
4133 P.OrigTerminalStopNumber
4134 )
4135 ) AS UP
4136
4137 --SUGGMIC: RE-WROTE THE REST OF THIS BLOCK FOR OBVIOUS REASONS, NONE OF THIS STUFF PAIRED THE DATE/TIMES TOGETHER AND SOME DATA WOULDN'T EVEN COME BACK
4138 INSERT INTO #TEMP_LFU_DATES (RecordID, DateType, DateValue, TImeValue, AggregatedResult)
4139 --PULL MAX DATE/TIMES
4140 SELECT
4141 R.RecordID,
4142 SD.DateType,
4143 SD.DateValue,
4144 SD.TimeValue,
4145 ROW_NUMBER() OVER (PARTITION BY R.RecordID, SD.DateType ORDER BY DateValue DESC, TimeValue DESC) AS AggregatedResult
4146 FROM #Row AS R
4147 INNER JOIN #InterLocation AS IL
4148 ON R.RecordID = IL.InterLocation_RecordID
4149
4150 INNER JOIN COLocation AS L WITH(NOLOCK)
4151 ON R.COSDetailID = L.COSDetailID
4152 INNER JOIN [#ILStopNumbers] AS S
4153 ON
4154 L.StopNumber = S.StopNumber
4155 AND R.RecordID = S.RecordID
4156 AND L.LocationType = S.LocationType
4157 INNER JOIN PDLocation AS PDL WITH(NOLOCK)
4158 ON
4159 L.COLocationID = PDL.COLocationID
4160 INNER JOIN [#SPODLocationDates_capture] SD
4161 ON PDL.SPODLocationID = SD.SPODLocationID
4162 WHERE DateType IN ('Destination Ramp Arrival Date','Destination Ramp Arrival Time','Destination Ramp Ramped Date','Destination Ramp Ramped Time','Destination Ramp ETA Date',
4163 'Destination Terminal ETA Date', 'Destination Terminal Arrival Date','Destination Terminal Arrival Time','Destination Terminal Departure Date','Destination Terminal Departure Time')
4164 AND (S.StopNumber = IL.DestRampStopNumber OR S.StopNumber = IL.DestTerminalStopNumber)
4165
4166 INSERT INTO #TEMP_LFU_DATES (RecordID, DateType, DateValue, TImeValue, AggregatedResult)
4167 --PULL MIN DATES/TIMES
4168 SELECT
4169 R.RecordID,
4170 SD.DateType,
4171 SD.DateValue,
4172 SD.TimeValue,
4173 ROW_NUMBER() OVER (PARTITION BY R.RecordID, SD.DateType ORDER BY DateValue ASC, TimeValue ASC) AS AggregatedResult
4174 FROM #Row AS R
4175 INNER JOIN #InterLocation AS IL
4176 ON R.RecordID = IL.InterLocation_RecordID
4177
4178 INNER JOIN COLocation AS L WITH(NOLOCK)
4179 ON R.COSDetailID = L.COSDetailID
4180 INNER JOIN [#ILStopNumbers] AS S
4181 ON
4182 L.StopNumber = S.StopNumber
4183 AND R.RecordID = S.RecordID
4184 AND L.LocationType = S.LocationType
4185 INNER JOIN PDLocation AS PDL WITH(NOLOCK)
4186 ON
4187 L.COLocationID = PDL.COLocationID
4188 INNER JOIN [#SPODLocationDates_capture] SD
4189 ON PDL.SPODLocationID = SD.SPODLocationID
4190 WHERE DateType NOT IN ('Destination Ramp Arrival Date','Destination Ramp Arrival Time','Destination Ramp Ramped Date','Destination Ramp Ramped Time','Destination Ramp ETA Date',
4191 'Destination Terminal ETA Date', 'Destination Terminal Arrival Date','Destination Terminal Arrival Time','Destination Terminal Departure Date','Destination Terminal Departure Time')
4192
4193
4194 INSERT INTO #TEMP_LFU_DATES (RecordID, DateType, DateValue, TImeValue, AggregatedResult)
4195 SELECT
4196 R.RecordID,
4197 SD.DateType,
4198 SD.DateValue,
4199 SD.TimeValue,
4200 ROW_NUMBER() OVER (PARTITION BY R.RecordID, SD.DateType ORDER BY DateValue ASC, TimeValue ASC) AS AggregatedResult
4201 FROM #Row AS R
4202 INNER JOIN Activity AS A WITH(NOLOCK)
4203 ON R.COServiceID = A.COServiceID
4204 INNER JOIN [#SPODates_capture] SD
4205 ON A.SPOrderID = SD.SPOrderID
4206
4207 INSERT INTO #TEMP_LFU_DATES (RecordID, DateType, DateValue, TImeValue, AggregatedResult)
4208 SELECT
4209 R.RecordID,
4210 SD.DateType,
4211 SD.DateValue,
4212 SD.TimeValue,
4213 ROW_NUMBER() OVER (PARTITION BY R.RecordID, SD.DateType ORDER BY DateValue ASC, TimeValue ASC) AS AggregatedResult
4214 FROM #Row AS R
4215 INNER JOIN dbo.LoadDate AS SD WITH (NOLOCK) ON R.LoadID = SD.LoadID
4216
4217 INSERT INTO #TEMP_LFU_DATES_PIVOTED (RecordID, OrigTerminalETADate, OrigTerminalArrivalDate, OrigTerminalDepartDate, OrigRampCutOffDate, OrigRampArrivalDate, OrigRampRampedDate,
4218 PortCutoffDate, OriginalPortETDDate, PortETDDate, OriginalPortETADate, PortETADate, ActualPortArrivalDate, ActualPortDepartDate, DestRampArrivalDate,
4219 DestRampDeRampedDate, RailETADate, DestRampETADate, DestTerminalETADate, DestTerminalArrivalDate, DestTerminalDepartDate, IMDLPromiseDate, EmptyReturnDate, LastFreeDate)
4220 SELECT
4221 RecordID,
4222 MIN([Origin Terminal ETA Date]) AS OrigTerminalETADate,
4223 MIN([Origin Terminal Arrival Date]) AS OrigTerminalArrivalDate,
4224 MIN([Origin Terminal Departure Date]) AS OrigTerminalDepartDate,
4225 MIN([Origin Ramp Cutoff Date]) AS OrigRampCutOffDate,
4226 MIN([Origin Ramp Arrival Date]) AS OrigRampArrivalDate,
4227 MIN([Origin Ramp Ramped Date]) AS OrigRampRampedDate,
4228 MIN([Port Cutoff Date]) AS PortCutoffDate,
4229 MIN([Original Port ETD Date]) AS OriginalPortETDDate,
4230 MIN([Port ETD Date]) AS PortETDDate,
4231 MIN([Original Port ETA Date]) AS OriginalPortETADate,
4232 MIN([Port ETA Date]) AS PortETADate,
4233 MIN([Actual Port Arrival Date]) AS ActualPortArrivalDate,
4234 MIN([Actual Port Departure Date]) AS ActualPortDepartDate,
4235 MIN([Destination Ramp Arrival Date]) AS DestRampArrivalDate,
4236 MIN([Destination Ramp Ramped Date]) AS DestRampDeRampedDate,
4237 MIN([Rail ETA Date]) AS RailETADate,
4238 MIN([Destination Ramp ETA Date]) AS DestRampETADate,
4239 MIN([Destination Terminal ETA Date]) AS DestTerminalETADate,
4240 MIN([Destination Terminal Arrival Date]) AS DestTerminalArrivalDate,
4241 MIN([Destination Terminal Departure Date]) AS DestTerminalDepartDate,
4242 MIN([IMDL Promise Date]) AS IMDLPromiseDate,
4243 MIN([EmptyReturnDate]) AS EmptyReturnDate,
4244 MIN([LastFreeDate]) AS LastFreeDate
4245 FROM (
4246 SELECT * FROM #TEMP_LFU_DATES WHERE AggregatedResult = 1
4247 ) T
4248 PIVOT (MIN(T.DateValue) FOR T.DateType IN
4249 (
4250 [Origin Terminal ETA Date],
4251 [Origin Terminal Arrival Date],
4252 [Origin Terminal Departure Date],
4253 [Origin Ramp Cutoff Date],
4254 [Origin Ramp Arrival Date],
4255 [Origin Ramp Ramped Date],
4256 [Port Cutoff Date],
4257 [Original Port ETD Date],
4258 [Port ETD Date],
4259 [Original Port ETA Date],
4260 [Port ETA Date],
4261 [Actual Port Arrival Date],
4262 [Actual Port Departure Date],
4263 [Destination Ramp Arrival Date],
4264 [Destination Ramp Ramped Date],
4265 [Rail ETA Date],
4266 [Destination Ramp ETA Date],
4267 [Destination Terminal ETA Date],
4268 [Destination Terminal Arrival Date],
4269 [Destination Terminal Departure Date],
4270 [IMDL Promise Date],
4271 [EmptyReturnDate],
4272 [LastFreeDate]
4273 )
4274 ) AS P
4275 GROUP BY RecordID
4276
4277 INSERT INTO #TEMP_LFU_TIMES_PIVOTED (RecordID, OrigTerminalArrivalTime, OrigTerminalDepartTime, OrigRampCutOffTime, OrigRampArrivalTime, OrigRampRampedTime, DestRampArrivalTime, DestRampDeRampedTime, DestTerminalArrivalTime, DestTerminalDepartTime)
4278 SELECT
4279 RecordID,
4280 MIN([Origin Terminal Arrival Date]) AS OrigTerminalArrivalTime,
4281 MIN([Origin Terminal Departure Date]) AS OrigTerminalDepartTime,
4282 MIN([Origin Ramp Cutoff Date]) AS OrigRampCutOffTime,
4283 MIN([Origin Ramp Arrival Date]) AS OrigRampArrivalTime,
4284 MIN([Origin Ramp Ramped Date]) AS OrigRampRampedTime,
4285 MIN([Destination Ramp Arrival Date]) AS DestRampArrivalTime,
4286 MIN([Destination Ramp Ramped Date]) AS DestRampDeRampedTime,
4287 MIN([Destination Terminal Arrival Date]) AS DestTerminalArrivalTime,
4288 MIN([Destination Terminal Departure Date]) AS DestTerminalDepartTime
4289 FROM (
4290 SELECT * FROM #TEMP_LFU_DATES WHERE AggregatedResult = 1
4291 ) T
4292 PIVOT (MIN(T.TimeValue) FOR T.DateType IN
4293 (
4294 [Origin Terminal Arrival Date],
4295 [Origin Terminal Departure Date],
4296 [Origin Ramp Cutoff Date],
4297 [Origin Ramp Arrival Date],
4298 [Origin Ramp Ramped Date],
4299 [Destination Ramp Arrival Date],
4300 [Destination Ramp Ramped Date],
4301 [Destination Terminal Arrival Date],
4302 [Destination Terminal Departure Date]
4303 )
4304 ) AS P
4305 GROUP BY RecordID
4306
4307 INSERT INTO #LFUDate
4308 (
4309 LFUDate_RecordID
4310 ,OrigTerminalETADate
4311 ,OrigTerminalArrivalDate
4312 ,OrigTerminalArrivalTime
4313 ,OrigTerminalDepartDate
4314 ,OrigTerminalDepartTime
4315 ,OrigRampCutOffDate
4316 ,OrigRampCutOffTime
4317 ,OrigRampArrivalDate
4318 ,OrigRampArrivalTime
4319 ,OrigRampRampedDate
4320 ,OrigRampRampedTime
4321 ,PortCutoffDate
4322 ,OriginalPortETDDate
4323 ,PortETDDate
4324 ,OriginalPortETADate
4325 ,PortETADate
4326 ,ActualPortArrivalDate
4327 ,ActualPortDepartDate
4328 ,DestRampArrivalDate
4329 ,DestRampArrivalTime
4330 ,DestRampDeRampedDate
4331 ,DestRampDeRampedTime
4332 ,RailETADate
4333 ,DestRampETADate
4334 ,DestTerminalETADate
4335 ,DestTerminalArrivalDate
4336 ,DestTerminalArrivalTime
4337 ,DestTerminalDepartDate
4338 ,DestTerminalDepartTime
4339 ,IMDLPromiseDate
4340 ,EmptyReturnDate
4341 ,LastFreeDate
4342 )
4343 SELECT
4344 D.RecordID
4345 ,OrigTerminalETADate
4346 ,OrigTerminalArrivalDate
4347 ,OrigTerminalArrivalTime
4348 ,OrigTerminalDepartDate
4349 ,OrigTerminalDepartTime
4350 ,OrigRampCutOffDate
4351 ,OrigRampCutOffTime
4352 ,OrigRampArrivalDate
4353 ,OrigRampArrivalTime
4354 ,OrigRampRampedDate
4355 ,OrigRampRampedTime
4356 ,PortCutoffDate
4357 ,OriginalPortETDDate
4358 ,PortETDDate
4359 ,OriginalPortETADate
4360 ,PortETADate
4361 ,ActualPortArrivalDate
4362 ,ActualPortDepartDate
4363 ,DestRampArrivalDate
4364 ,DestRampArrivalTime
4365 ,DestRampDeRampedDate
4366 ,DestRampDeRampedTime
4367 ,RailETADate
4368 ,DestRampETADate
4369 ,DestTerminalETADate
4370 ,DestTerminalArrivalDate
4371 ,DestTerminalArrivalTime
4372 ,DestTerminalDepartDate
4373 ,DestTerminalDepartTime
4374 ,IMDLPromiseDate
4375 ,EmptyReturnDate
4376 ,LastFreeDate
4377 FROM #TEMP_LFU_DATES_PIVOTED D
4378 INNER JOIN #TEMP_LFU_TIMES_PIVOTED T ON D.RecordID = T.RecordID
4379 END
4380
4381
4382 -- OK02062008=============================================================================================
4383-- Load #Invoice
4384 -- =======================================================================================================
4385
4386 --PRINT 'Load Invoice'
4387
4388 -- Only one CHRListBillNum per shipment
4389 -- Remember that string index starts at 1 in SQL instead of 0 (like in C#)
4390 IF @ProcessInvoices = 1
4391 BEGIN
4392
4393
4394 CREATE TABLE #FilteredOrderInvoice
4395 (
4396 COServiceID INT,
4397 OrderInvoiceID INT
4398 )
4399
4400 IF @InvoiceNumber IS NOT NULL
4401 BEGIN
4402 INSERT INTO #FilteredOrderInvoice
4403 SELECT DISTINCT R.COServiceID, OI.OrderInvoiceID
4404 FROM #Row R
4405 INNER JOIN COServiceInvoice AS CSI2 WITH(NOLOCK) ON (CSI2.COServiceID = R.COServiceID OR CSI2.COServiceID = R.CustomsCOServiceID)
4406 INNER JOIN OrderInvoice AS OI ON OI.OrderInvoiceID = CSI2.OrderInvoiceID
4407 INNER JOIN #InvoiceNumber AS I ON I.InvoiceNumber = OI.InvoiceNumber
4408 END
4409 ELSE
4410 BEGIN
4411 INSERT INTO #FilteredOrderInvoice
4412 SELECT DISTINCT R.COServiceID, OI.OrderInvoiceID
4413 FROM #Row R
4414 INNER JOIN COServiceInvoice AS CSI2 WITH(NOLOCK) ON (CSI2.COServiceID = R.COServiceID OR CSI2.COServiceID = R.CustomsCOServiceID)
4415 INNER JOIN OrderInvoice AS OI ON OI.OrderInvoiceID = CSI2.OrderInvoiceID
4416
4417 END
4418
4419
4420
4421
4422 -- Why is InvoiceNumber null for every record in OrderInvoice table?
4423 -- sub-selects probably need sessionviewid filter as well!!!!
4424 -- process records with multiple invoices (build up comma-delimited value)
4425 INSERT INTO #Invoice
4426 (
4427 Invoice_RecordID,
4428 InvoiceDate,
4429 InvoiceNum,
4430 CHRListBillNum,
4431 InvoiceReleaseDate,
4432 InvoiceBalance,
4433 ReceivedAmount
4434 )
4435 SELECT
4436 R.RecordID,
4437 MIN(InvoiceDate.DateValue),
4438 (SELECT DISTINCT CAST(ISNULL(InvoiceNumber,InvoiceID) AS VARCHAR(250)) + ', '
4439 FROM OrderInvoice AS OI2 WITH(NOLOCK)
4440 INNER JOIN COServiceInvoice AS I2 WITH(NOLOCK)
4441 ON OI2.OrderInvoiceID = I2.OrderInvoiceID
4442 INNER JOIN #Row AS R2
4443 ON (I2.COServiceID = R2.COServiceID OR I2.COServiceID = R2.CustomsCOServiceID)
4444 WHERE R2.RecordID = R.RecordID
4445 FOR XML PATH('')) AS InvoiceNumbers,
4446 NULLIF(MIN(ISNULL(OI.ListBillID, 99990909)), 99990909),
4447 MIN(ReleaseDate.DateValue),
4448 SUM(ISNULL(OI.InvoiceBalance, 0)) AS InvoiceBalance,
4449 SUM(ISNULL(OI.ReceivedAmount, 0)) AS ReceivedAmount
4450 FROM #Row AS R
4451 INNER JOIN COServiceInvoice AS I WITH(NOLOCK)
4452 ON (R.COServiceID = I.COServiceID OR R.CustomsCOServiceID = I.COServiceID)
4453 INNER JOIN OrderInvoice AS OI WITH(NOLOCK)
4454 ON I.OrderInvoiceID = OI.OrderInvoiceID
4455 INNER JOIN #FilteredOrderInvoice AS FI ON FI.OrderInvoiceID = OI.OrderInvoiceID
4456 INNER JOIN OrderInvoiceParty AS OIP WITH(NOLOCK)
4457 ON OI.OrderInvoiceID = OIP.OrderInvoiceID
4458 INNER JOIN OrderParty AS OP WITH(NOLOCK)
4459 ON OIP.OrderPartyID = OP.OrderPartyID
4460 INNER JOIN #UserCCodes AS CC
4461ON OP.PartyCode = CC.CompanyCode
4462 LEFT OUTER JOIN OrderInvoiceDate AS InvoiceDate WITH (NOLOCK)
4463 ON InvoiceDate.OrderInvoiceID = OI.OrderInvoiceID
4464 AND InvoiceDate.DateType = 'Invoice Date'
4465 LEFT OUTER JOIN OrderInvoiceDate AS ReleaseDate WITH (NOLOCK)
4466 ON OI.OrderInvoiceID = ReleaseDate.OrderInvoiceID
4467 AND ReleaseDate.DateType = 'Invoice Released Date'
4468 WHERE MultiLegFlg = 0 OR @SummarizeShipment = 0
4469 GROUP BY R.RecordID
4470 HAVING COUNT(DISTINCT ISNULL(InvoiceNumber, InvoiceID)) > 1
4471
4472 UPDATE #Invoice SET InvoiceStatus = 'Invoice Paid'
4473 WHERE InvoiceBalance = 0
4474
4475 UPDATE #Invoice SET InvoiceStatus = 'Invoice Partially Paid'
4476 WHERE ReceivedAmount > 0 AND InvoiceBalance > 0
4477
4478 UPDATE #Invoice SET InvoiceStatus = 'Invoice Not Paid'
4479 WHERE InvoiceBalance > 0 AND ISNULL(ReceivedAmount, 0) = 0
4480
4481 -- Process one to one (no need for overhead of sub-select for xml path query)
4482 -- TODO : A COService can have multiple invoices; this isn't covered in the
4483 -- previous query because we group by RecordID, and we would have only one
4484 -- COService per RecordID.
4485 INSERT INTO #Invoice (
4486 Invoice_RecordID,
4487 InvoiceDate,
4488 InvoiceNum,
4489 CHRListBillNum,
4490 InvoiceReleaseDate,
4491 InvoiceBalance,
4492 InvoiceStatus,
4493 ReceivedAmount
4494)
4495 SELECT DISTINCT
4496 R.RecordID,
4497 InvoiceDate.DateValue,
4498 ISNULL(OI.InvoiceNumber, OI.InvoiceID),
4499 OI.ListBillID,
4500 ReleaseDate.DateValue,
4501 OI.InvoiceBalance,
4502 CASE
4503 WHEN OI.InvoiceBalance = 0 THEN 'Invoice Paid'
4504 WHEN OI.ReceivedAmount > 0 AND OI.InvoiceBalance > 0 THEN 'Invoice Partially Paid'
4505 WHEN OI.InvoiceBalance > 0 THEN 'Invoice Not Paid'
4506 END AS InvoiceStatus ,
4507 OI.ReceivedAmount
4508 FROM #Row AS R
4509 INNER JOIN COServiceInvoice AS I WITH(NOLOCK)
4510 ON (R.COServiceID = I.COServiceID OR R.CustomsCOServiceID = I.COServiceID)
4511 INNER JOIN OrderInvoice AS OI WITH(NOLOCK)
4512 ON I.OrderInvoiceID = OI.OrderInvoiceID
4513 INNER JOIN #FilteredOrderInvoice AS FI ON FI.OrderInvoiceID = OI.OrderInvoiceID
4514 INNER JOIN OrderInvoiceParty AS OIP WITH(NOLOCK)
4515 ON OI.OrderInvoiceID = OIP.OrderInvoiceID
4516 INNER JOIN OrderParty AS OP WITH(NOLOCK)
4517 ON OIP.OrderPartyID = OP.OrderPartyID
4518 INNER JOIN #UserCCodes AS CC
4519 ON OP.PartyCode = CC.CompanyCode
4520 LEFT OUTER JOIN OrderInvoiceDate AS InvoiceDate WITH (NOLOCK)
4521 ON InvoiceDate.OrderInvoiceID = OI.OrderInvoiceID
4522 AND InvoiceDate.DateType = 'Invoice Date'
4523 LEFT OUTER JOIN OrderInvoiceDate AS ReleaseDate WITH (NOLOCK)
4524 ON OI.OrderInvoiceID = ReleaseDate.OrderInvoiceID
4525 AND ReleaseDate.DateType = 'Invoice Released Date'
4526 LEFT OUTER JOIN #Invoice AS T
4527 ON R.RecordID = T.Invoice_RecordID
4528 WHERE T.Invoice_RecordID IS NULL AND (MultiLegFlg = 0 OR @SummarizeShipment = 0)
4529
4530 IF (EXISTS(SELECT TOP 1 1 FROM #Row WHERE MultiLegFlg = 1 AND @SummarizeShipment = 1))
4531 BEGIN
4532 INSERT INTO #Invoice
4533 (
4534 Invoice_RecordID,
4535 InvoiceDate,
4536 InvoiceNum,
4537 CHRListBillNum,
4538 InvoiceReleaseDate,
4539 InvoiceBalance,
4540 ReceivedAmount
4541 )
4542 SELECT
4543 R.RecordID,
4544 MIN(InvoiceDate.DateValue),
4545 (SELECT DISTINCT CAST(ISNULL(InvoiceNumber,InvoiceID) AS VARCHAR(250)) + ', '
4546 FROM OrderInvoice AS OI2 WITH(NOLOCK)
4547 INNER JOIN COServiceInvoice AS I2 WITH(NOLOCK)
4548 ON OI2.OrderInvoiceID = I2.OrderInvoiceID
4549 INNER JOIN #Row AS R2
4550 ON (I2.COServiceID = R2.COServiceID OR R2.CustomsCOServiceID = I2.COServiceID)
4551 WHERE R2.RecordID = R.RecordID
4552 FOR XML PATH('')) AS InvoiceNumbers,
4553 NULLIF(MIN(ISNULL(OI.ListBillID, 99990909)), 99990909),
4554 MIN(ReleaseDate.DateValue),
4555 SUM(ISNULL(OI.InvoiceBalance, 0)) AS InvoiceBalance,
4556 SUM(ISNULL(OI.ReceivedAmount, 0)) AS ReceivedAmount
4557 FROM #Row AS R
4558 INNER JOIN COServiceInvoice AS I WITH(NOLOCK)
4559 ON (R.COServiceID = I.COServiceID OR R.CustomsCOServiceID = I.COServiceID)
4560 INNER JOIN OrderInvoice AS OI WITH(NOLOCK)
4561 ON I.OrderInvoiceID = OI.OrderInvoiceID
4562 INNER JOIN #FilteredOrderInvoice AS FI
4563 ON FI.OrderInvoiceID = OI.OrderInvoiceID
4564 INNER JOIN OrderInvoiceParty AS OIP WITH(NOLOCK)
4565 ON OI.OrderInvoiceID = OIP.OrderInvoiceID
4566 INNER JOIN OrderParty AS OP WITH(NOLOCK)
4567 ON OIP.OrderPartyID = OP.OrderPartyID
4568 INNER JOIN #UserCCodes AS CC
4569 ON OP.PartyCode = CC.CompanyCode
4570 LEFT OUTER JOIN OrderInvoiceDate AS InvoiceDate WITH (NOLOCK)
4571 ON InvoiceDate.OrderInvoiceID = OI.OrderInvoiceID
4572 AND InvoiceDate.DateType = 'Invoice Date'
4573 LEFT OUTER JOIN OrderInvoiceDate AS ReleaseDate WITH (NOLOCK)
4574 ON OI.OrderInvoiceID = ReleaseDate.OrderInvoiceID
4575 AND ReleaseDate.DateType = 'Invoice Released Date'
4576 WHERE MultiLegFlg = 1 AND R.LoadNumber = OI.LoadNumber
4577 GROUP BY R.RecordID
4578 HAVING COUNT(DISTINCT ISNULL(InvoiceNumber, InvoiceID)) > 1
4579
4580 UPDATE #Invoice SET InvoiceStatus = 'Invoice Paid'
4581 WHERE InvoiceBalance = 0
4582
4583 UPDATE #Invoice SET InvoiceStatus = 'Invoice Partially Paid'
4584 WHERE ReceivedAmount > 0 AND InvoiceBalance > 0
4585
4586 UPDATE #Invoice SET InvoiceStatus = 'Invoice Not Paid'
4587 WHERE InvoiceBalance > 0 AND ISNULL(ReceivedAmount, 0) = 0
4588
4589 -- Process one to one (no need for overhead of sub-select for xml path query)
4590 -- TODO : A COService can have multiple invoices; this isn't covered in the
4591 -- previous query because we group by RecordID, and we would have only one
4592 -- COService per RecordID.
4593 INSERT INTO #Invoice (
4594 Invoice_RecordID,
4595 InvoiceDate,
4596 InvoiceNum,
4597 CHRListBillNum,
4598 InvoiceReleaseDate,
4599 InvoiceBalance,
4600 InvoiceStatus,
4601 ReceivedAmount
4602 )
4603 SELECT DISTINCT
4604 R.RecordID,
4605 InvoiceDate.DateValue,
4606 ISNULL(OI.InvoiceNumber, OI.InvoiceID),
4607 OI.ListBillID,
4608 ReleaseDate.DateValue,
4609 OI.InvoiceBalance,
4610 CASE
4611 WHEN OI.InvoiceBalance = 0 THEN 'Invoice Paid'
4612 WHEN OI.ReceivedAmount > 0 AND OI.InvoiceBalance > 0 THEN 'Invoice Partially Paid'
4613 WHEN OI.InvoiceBalance > 0 THEN 'Invoice Not Paid'
4614 END AS InvoiceStatus,
4615 OI.ReceivedAmount
4616 FROM #Row AS R
4617 INNER JOIN COServiceInvoice AS I WITH(NOLOCK)
4618 ON (R.COServiceID = I.COServiceID OR R.CustomsCOServiceID = I.COServiceID)
4619 INNER JOIN OrderInvoice AS OI WITH(NOLOCK)
4620 ON I.OrderInvoiceID = OI.OrderInvoiceID
4621 INNER JOIN #FilteredOrderInvoice AS FI
4622 ON FI.OrderInvoiceID = OI.OrderInvoiceID
4623 INNER JOIN OrderInvoiceParty AS OIP WITH(NOLOCK)
4624 ON OI.OrderInvoiceID = OIP.OrderInvoiceID
4625 INNER JOIN OrderParty AS OP WITH(NOLOCK)
4626 ON OIP.OrderPartyID = OP.OrderPartyID
4627 INNER JOIN #UserCCodes AS CC
4628 ON OP.PartyCode = CC.CompanyCode
4629 LEFT OUTER JOIN OrderInvoiceDate AS InvoiceDate WITH (NOLOCK)
4630 ON InvoiceDate.OrderInvoiceID = OI.OrderInvoiceID
4631 AND InvoiceDate.DateType = 'Invoice Date'
4632 LEFT OUTER JOIN OrderInvoiceDate AS ReleaseDate WITH (NOLOCK)
4633 ON OI.OrderInvoiceID = ReleaseDate.OrderInvoiceID
4634 AND ReleaseDate.DateType = 'Invoice Released Date'
4635 LEFT OUTER JOIN #Invoice AS T
4636 ON R.RecordID = T.Invoice_RecordID
4637 WHERE T.Invoice_RecordID IS NULL AND MultiLegFlg = 1 AND R.LoadNumber = OI.LoadNumber
4638 END
4639
4640 UPDATE #Invoice SET InvoiceTotal = ISNULL(InvoiceBalance, 0) + ISNULL(ReceivedAmount, 0)
4641
4642 /****************************************************************************************************************************
4643 Work around to filter out records that do not meet the original report criteria. There isn't an easy way to filter these
4644 out sooner since one COServiceID can have multiple OrderInvoice records
4645 ****************************************************************************************************************************/
4646 IF @ListBillNumber IS NOT NULL OR @InvoiceNumber IS NOT NULL OR @DateType = 'InvoicePrintDate'
4647 BEGIN
4648 IF @ListBillNumber IS NOT NULL
4649 BEGIN
4650 --*** Delete #Row records
4651 DELETE R
4652 FROM #Invoice I
4653 INNER JOIN #Row R ON R.RecordID = I.Invoice_RecordID
4654 WHERE
4655 I.CHRListBillNum IS NOT NULL
4656 AND NOT EXISTS(SELECT 1 FROM #ListBillNumber T WHERE I.CHRListBillNum = T.ListBillNumber)
4657
4658 --*** Delete #Invoice records
4659 DELETE I
4660 FROM #Invoice I
4661 WHERE
4662 I.CHRListBillNum IS NOT NULL
4663 AND NOT EXISTS(SELECT 1 FROM #ListBillNumber T WHERE I.CHRListBillNum = T.ListBillNumber)
4664 END
4665
4666 IF @InvoiceNumber IS NOT NULL
4667 BEGIN
4668 --*** Delete #Row records
4669 DELETE R
4670 FROM #Row R
4671 WHERE NOT EXISTS(
4672 SELECT 1 FROM #Invoice I WHERE I.Invoice_RecordID = R.RecordID)
4673 END
4674 END
4675 --*********************************************************************************************************
4676
4677 END
4678
4679 -- OK02062008=============================================================================================
4680 -- Load #Item
4681 -- =======================================================================================================
4682
4683 --PRINT 'Load Item'
4684 --03/04/2008 Steve No longer need to check for additional fields.
4685 -- Moved these fields up to where @processitem is set
4686 IF @ProcessItems = 1 --OR EXISTS(SELECT 1 FROM #Column WHERE CName IN
4687-- (
4688-- 'UPC',
4689-- 'NMFC',
4690-- 'CustSpecific1',
4691-- 'CustSpecific2',
4692-- 'ProductCode',
4693-- 'PLU',
4694-- 'EAN',
4695-- 'HTCode',
4696-- 'ItemRefNums'
4697-- )
4698-- )
4699
4700 BEGIN
4701 INSERT INTO #Item
4702 (
4703 Item_RecordID,
4704 ItemID,
4705 ExFactoryDate,
4706 ActualQuantity,
4707 HazardousItem,
4708 Class,
4709 CommodityCategory,
4710 [Value],
4711 ExpectedQuantity,
4712 [Weight],
4713 TempSensitive,
4714 SKU,
4715 CustCommodityCode,
4716 Pallets,
4717 UnitOfMeasure,
4718 CustCommodityName,
4719 DimensionalWeight,
4720 PalletSpaces,
4721 ItemDescription,
4722 ActualEDIPackagingCode,
4723 ActualVolume,
4724 Hot,
4725 InnerPack,
4726 UnitsPerPallet,
4727 MasterPack,
4728 ItemLength,
4729 ItemWidth,
4730 ItemHeight,
4731 OriginalFreightClass,
4732 OriginalPallets,
4733 OriginalPalletSpaces,
4734 OriginalQuantity,
4735 OriginalWeight,
4736 OriginalVolume,
4737 OriginalNMFC,
4738 ExpectedMinWeight,
4739 ExpectedMaxWeight
4740 )
4741
4742 SELECT
4743 R.RecordID AS Item_RecordID,
4744 I.COItemID AS ItemID,
4745 I.ExFactoryDate AS ExFactoryDate,
4746 I.ActualQuantity AS ActualQuantity,
4747 I.Hazardous AS HazardousItem,
4748 CASE ISNULL(I.ActualFreightClass, '')
4749 when '' THEN ISNULL(I.Class, '')
4750 Else I.ActualFreightClass
4751 END as Class,
4752 I.CommodityCategory AS CommodityCategory,
4753 I.[Value] AS [Value],
4754 I.ExpectedQuantity AS ExpectedQuantity,
4755 I.ActualWeight AS [Weight],
4756 I.TempSensitive AS TempSensitive,
4757 I.SKU AS SKU,
4758 I.CustomerCommodityCode AS CustCommodityCode,
4759 ISNULL(
4760 I.ActualPallets,
4761 I.ExpectedPallets) AS Pallets,
4762 I.UOM AS UnitOfMeasure,
4763 ISNULL(
4764 I.CustomerCommodityName,
4765 I.Commodity) AS CustCommodityName,
4766 I.DimensionWeight AS DimensionalWeight,
4767 I.PalletSpaces AS PalletSpaces,
4768 SUBSTRING(
4769 I.Description,
4770 1,500) AS ItemDescription, -- 04/25/2008 Ensure that long descriptions don't cause errors
4771 I.ActualUOM AS ActualEDIPackagingCode,
4772 COALESCE(
4773 I.ActualVolume,
4774 I.ExpectedVolume,
4775 0) AS ActualVolume,
4776 COALESCE(
4777 NULLIF(R.HotFlg, 0),
4778 I.HotFlg,
4779 0) AS Hot,
4780 I.InnerPackQuantity AS InnerPack,
4781 CAST(ISNULL(I.ActualQuantity, I.ExpectedQuantity) / ISNULL(NULLIF(I.ActualPallets, 0), NULLIF(I.ExpectedPallets, 0)) AS DECIMAL(19,2)) AS UnitsPerPallet,
4782 CAST(I.InnerPackQuantity / ISNULL(NULLIF(I.ActualQuantity, 0), NULLIF(I.ExpectedQuantity, 0)) AS INT) AS MasterPack,
4783 I.UnitLength AS ItemLength,
4784 I.UnitWidth AS ItemWidth,
4785 I.UnitHeight AS ItemHeight,
4786 I.OriginalFreightClass AS OriginalClass,
4787 I.OriginalPallets,
4788 I.OriginalPalletSpaces,
4789 I.OriginalQuantity,
4790 I.OriginalWeight,
4791 I.OriginalVolume,
4792 I.OriginalNMFC,
4793 I.ExpectedMinWeight,
4794 I.ExpectedMaxWeight
4795 FROM [#Row] AS R
4796 INNER JOIN COItem AS I WITH(NOLOCK)
4797 ON R.COSDetailID = I.COSDetailID --AND I.COItemID = R.COItemID
4798 AND (ISNULL(I.ExcludeFromAES,0) = 0 OR (ISNULL(I.ExcludeFromAES,0) = 1 AND ISNULL(I.ExcludeFromBL,0) = 1))
4799 END
4800
4801 IF @ProcessFlatbed = 1
4802 BEGIN
4803 INSERT INTO #ItemFlatbed
4804 (
4805 ItemFlatbed_RecordID
4806 ,Overdimensional
4807 ,EquipmentTypeCode
4808 ,TarpLength
4809 ,RequiredChains
4810 ,RequiredStraps
4811 ,CoilRacks
4812 ,LoadingType
4813 ,ItemFlatbedID
4814 )
4815 SELECT
4816 I.Item_RecordID AS ItemFlatbed_RecordID,
4817 ISNULL(F.ODFlg, 0) AS OverDimensional,
4818 F.EquipmentTypeCode AS EquipmentTypeCode,
4819 F.TarpType AS TarpLength,
4820 F.RequiredChainsCount AS RequiredChains,
4821 F.RequiredStrapsCount AS RequiredStraps,
4822 F.CoilRacksCount AS CoilRacks,
4823 F.LoadingTypeCode AS LoadingType,
4824 F.COItemID
4825 FROM #Item AS I
4826 INNER JOIN COItemFlatbed AS F WITH (NOLOCK)
4827 ON I.ItemID = F.COItemID
4828 END
4829
4830 -- OK02062008=============================================================================================
4831 -- Load #ItemSummary
4832 -- =======================================================================================================
4833
4834 --PRINT 'Load ItemSummary'
4835
4836 IF @ProcessItemSummaries = 1
4837 BEGIN
4838 INSERT INTO #ItemSummary
4839 (
4840 ItemSummary_RecordID,
4841 SummaryActualQuantity,
4842 SummaryExpectedQuantity,
4843 SummaryActualPallets,
4844 SummaryExpectedPallets,
4845 SummaryActualWeight,
4846 SummaryExpectedMinWeight,
4847 SummaryHazardous,
4848 SummaryPalletSpaces,
4849 SummaryExpectedMaxWeight,
4850 SummaryVolume,
4851 SummaryDimensionalWeight,
4852 SummaryChargeableWeight,
4853 SummaryUnitOfMeasure,
4854 SummaryHot,
4855 SummaryInnerPack,
4856SummaryOverDimensional,
4857 SummaryOriginalPallets,
4858 SummaryOriginalPalletSpaces,
4859 SummaryOriginalQuantity,
4860 SummaryOriginalWeight,
4861 SummaryOriginalVolume
4862 )
4863
4864 SELECT
4865 R.RecordID AS Item_RecordID,
4866 SUM(ISNULL(I.ActualQuantity, 0)) AS SummaryActualQuantity,
4867 SUM(ISNULL(I.ExpectedQuantity, 0)) AS SummaryExpectedQuantity,
4868 SUM(ISNULL(I.ActualPallets, 0)) AS SummaryActualPallets,
4869 SUM(ISNULL(I.ExpectedPallets, 0)) AS SummaryExpectedPallets,
4870 SUM(ISNULL(I.ActualWeight, 0)) AS SummaryActualWeight,
4871 SUM(ISNULL(I.ExpectedMinWeight, 0)) AS SummaryExpectedMinWeight,
4872 MAX(ISNULL(CAST(I.Hazardous AS INT), 0)) AS SummaryHazardous,
4873 SUM(ISNULL(I.PalletSpaces, 0)) AS SummaryPalletSpaces,
4874 SUM(ISNULL(I.ExpectedMaxWeight, 0)) AS SummaryExpectedMaxWeight,
4875 SUM(COALESCE(
4876 I.ActualVolume,
4877 I.ExpectedVolume,
4878 0)) AS SummaryVolume,
4879 SUM(ISNULL(I.DimensionWeight, 0)) AS SummaryDimensionalWeight,
4880 NULL AS SummaryChargeableWeight,
4881 CASE COUNT(DISTINCT I.ActualUOM)
4882 WHEN 1 THEN MAX(I.ActualUOM)
4883 ELSE 'Pieces'
4884 END AS SummaryUnitOfMeasure,
4885 MAX(COALESCE(
4886 NULLIF(CAST(R.HotFlg AS INT), 0),
4887 CAST(I.HotFlg AS INT),
4888 0)) AS SummarHot,
4889 SUM(ISNULL(I.InnerPackQuantity, 0)) AS SummaryInnerPack,
4890 MAX(ISNULL(F.ODFlg, 0)) AS SummaryOverDimensional,
4891 SUM(ISNULL(OriginalPallets, 0)),
4892 SUM(ISNULL(OriginalPalletSpaces, 0)),
4893 SUM(ISNULL(OriginalQuantity, 0)),
4894 SUM(ISNULL(OriginalWeight, 0)),
4895 SUM(ISNULL(OriginalVolume, 0))
4896 FROM #Row AS R
4897 INNER JOIN COItem AS I WITH(NOLOCK)
4898 ON R.COSDetailID = I.COSDetailID
4899 AND ISNULL(I.ExcludeFromBL,0) = 0
4900 /*NEW OR CHANGED Jeremy Dixon 1/2014*/
4901 LEFT JOIN COItemFlatbed AS F WITH (NOLOCK)
4902 ON I.COItemID = F.COItemID
4903
4904 GROUP BY R.RecordID
4905
4906 /*NEW OR CHANGED Jeremy Dixon 1/2014*/
4907 INSERT INTO #ItemSummary
4908 (
4909 ItemSummary_RecordID,
4910 SummaryActualQuantity,
4911 SummaryExpectedQuantity,
4912 SummaryActualPallets,
4913 SummaryExpectedPallets,
4914 SummaryActualWeight,
4915 SummaryExpectedMinWeight,
4916 SummaryHazardous,
4917 SummaryPalletSpaces,
4918 SummaryExpectedMaxWeight,
4919 SummaryVolume,
4920 SummaryDimensionalWeight,
4921 SummaryChargeableWeight,
4922 SummaryUnitOfMeasure,
4923 SummaryHot,
4924 SummaryInnerPack,
4925 SummaryOverDimensional,
4926 SummaryOriginalPallets,
4927 SummaryOriginalPalletSpaces,
4928 SummaryOriginalQuantity,
4929 SummaryOriginalWeight,
4930 SummaryOriginalVolume
4931 )
4932 SELECT
4933 R.RecordID AS Item_RecordID,
4934 SUM(ISNULL(I.ActualQuantity, 0)) AS SummaryActualQuantity,
4935 SUM(ISNULL(I.ExpectedQuantity, 0)) AS SummaryExpectedQuantity,
4936 SUM(ISNULL(I.ActualPallets, 0)) AS SummaryActualPallets,
4937 SUM(ISNULL(I.ExpectedPallets, 0)) AS SummaryExpectedPallets,
4938 SUM(ISNULL(I.ActualWeight, 0)) AS SummaryActualWeight,
4939 SUM(ISNULL(I.ExpectedMinWeight, 0)) AS SummaryExpectedMinWeight,
4940 MAX(ISNULL(CAST(I.Hazardous AS INT), 0)) AS SummaryHazardous,
4941 SUM(ISNULL(I.PalletSpaces, 0)) AS SummaryPalletSpaces,
4942 SUM(ISNULL(I.ExpectedMaxWeight, 0)) AS SummaryExpectedMaxWeight,
4943 SUM(COALESCE(
4944 I.ActualVolume,
4945 I.ExpectedVolume,
4946 0)) AS SummaryVolume,
4947 SUM(ISNULL(I.DimensionWeight, 0)) AS SummaryDimensionalWeight,
4948 NULL AS SummaryChargeableWeight,
4949 CASE COUNT(DISTINCT I.ActualUOM)
4950 WHEN 1 THEN MAX(I.ActualUOM)
4951 ELSE 'Pieces'
4952 END AS SummaryUnitOfMeasure,
4953 MAX(COALESCE(
4954 NULLIF(CAST(R.HotFlg AS INT), 0),
4955 CAST(I.HotFlg AS INT),
4956 0)) AS SummarHot,
4957 SUM(ISNULL(I.InnerPackQuantity, 0)) AS SummaryInnerPack,
4958 0 AS SummaryOverDimensional,
4959 SUM(ISNULL(OriginalPallets, 0)),
4960 SUM(ISNULL(OriginalPalletSpaces, 0)),
4961 SUM(ISNULL(OriginalQuantity, 0)),
4962 SUM(ISNULL(OriginalWeight, 0)),
4963 SUM(ISNULL(OriginalVolume, 0))
4964 FROM (
4965 SELECT Rw.RecordID, Rw.COSDetailID, Rw.HotFlg
4966 FROM #Row AS Rw
4967 LEFT OUTER JOIN #ItemSummary AS F WITH (NOLOCK)
4968 ON F.ItemSummary_RecordID = Rw.RecordID
4969 WHERE F.ItemSummary_RecordID IS NULL
4970 ) AS R
4971 INNER JOIN COItem AS I WITH(NOLOCK)
4972 ON R.COSDetailID = I.COSDetailID
4973 GROUP BY R.RecordID
4974-- OPTION (LOOP JOIN)
4975
4976 UPDATE #ItemSummary
4977 SET
4978 SummaryChargeableWeight =
4979 CASE
4980 WHEN SummaryDimensionalWeight > SummaryActualWeight
4981 THEN SummaryDimensionalWeight
4982 ELSE SummaryActualWeight
4983 END
4984 END
4985
4986 -- =======================================================================================================
4987 -- Load #DriverTixSummary
4988 -- =======================================================================================================
4989
4990 --PRINT 'Load DriverTixSummary'
4991
4992 IF @ProcessDriverTixSummaries = 1
4993 BEGIN
4994 INSERT INTO [#DriverTixSummary]
4995 (
4996 DriverTixSummary_RecordID,
4997 SummaryDriverHeavyWeightTix,
4998 SummaryDriverLightWeightTix
4999 )
5000
5001 SELECT
5002 R.RecordID AS DriverTixSummary_RecordID,
5003 MAX(S.DriverHeavyWeightTix) AS SummaryDriverHeavyWeightTix,
5004 MAX(S.DriverLightWeightTix) AS SummaryDriverLightWeightTix
5005 FROM #Row AS R
5006 INNER JOIN #SPODetailID AS PD
5007 ON R.COSDetailID = PD.COSDetailID
5008 INNER JOIN SPODetail AS S WITH(NOLOCK)
5009 ON PD.SPODetailID = S.SPODetailID
5010 GROUP BY R.RecordID
5011 END
5012
5013
5014 -- OK02082008=============================================================================================
5015 -- Load #ItemSummaryText
5016 -- =============================================================================================
5017
5018 --PRINT 'Load ItemSummaryText'
5019
5020 IF @ProcessItemSummaryTexts = 1
5021 BEGIN
5022 INSERT INTO [#ItemSummaryText] (ItemSummaryText_RecordID,SummaryCommodity,SummaryDescription)
5023 SELECT DISTINCT
5024 R.RecordID,
5025 Item.Commodity,
5026 Item.Description
5027 FROM [#Row] AS R
5028 INNER JOIN COItem AS Item WITH (NOLOCK)
5029 ON R.COSDetailID = Item.COSDetailID AND ISNULL(Item.ExcludeFromBL,0) = 0
5030
5031 UPDATE IST
5032 SET DeleteFlg = 1
5033 FROM #ItemSummaryText AS IST
5034 WHERE EXISTS (SELECT 1 FROM #ItemSummaryText AS IST2
5035 WHERE IST.ItemSummaryText_RecordID = IST2.ItemSummaryText_RecordID
5036 GROUP BY IST2.ItemSummaryText_RecordID
5037 HAVING COUNT(1) > 1
5038 )
5039
5040 INSERT INTO [#ItemSummaryText] (ItemSummaryText_RecordID,SummaryCommodity,SummaryDescription)
5041 SELECT DISTINCT
5042 IST.ItemSummaryText_RecordID,
5043 SUBSTRING((
5044 SELECT IST2.SummaryCommodity + ', '
5045 FROM #ItemSummaryText AS IST2
5046 WHERE IST.ItemSummaryText_RecordID = IST2.ItemSummaryText_RecordID
5047 GROUP BY SummaryCommodity
5048 FOR XML PATH('')
5049 ),0,2007) AS SummaryCommodity,
5050 SUBSTRING((
5051SELECT IST3.SummaryDescription + ', '
5052 FROM #ItemSummaryText AS IST3
5053 WHERE IST.ItemSummaryText_RecordID = IST3.ItemSummaryText_RecordID
5054 GROUP BY SummaryDescription
5055 FOR XML PATH('')
5056 ),0,2007) AS SummaryDescription
5057 FROM #ItemSummaryText AS IST
5058 WHERE DeleteFlg = 1
5059
5060 DELETE FROM #ItemSummaryText WHERE DeleteFlg = 1
5061END
5062
5063 -- OK02082008=============================================================================================
5064 -- Load #Comment
5065 -- =======================================================================================================
5066
5067 --PRINT 'Load Comment'
5068
5069 IF @ProcessComments = 1
5070 BEGIN
5071 INSERT INTO #Comment(Comment_RecordID, Comment)
5072 SELECT DISTINCT
5073 R.RecordID AS Comment_RecordID,
5074 CSC.Comment AS Comment
5075 FROM [#Row] AS R
5076 INNER JOIN COServiceComment AS CSC WITH(NOLOCK)
5077 ON R.COServiceID = CSC.COServiceID
5078 --AND R.LevelNumber = 1
5079
5080 UPDATE C
5081 SET DeleteFlg = 1
5082 FROM [#Comment] AS C
5083 WHERE EXISTS
5084 (
5085 SELECT 1
5086 FROM [#Comment] AS C2
5087 WHERE C2.Comment_RecordID = C.Comment_RecordID
5088 GROUP BY C2.Comment_RecordID
5089 HAVING COUNT(1) > 1
5090 )
5091
5092 -- 11/12/2008 GANASAD Because 99% of Express comments are internal, we're not going
5093 -- to show Express comments unless the user specifically is cleared to see them.
5094 IF @HideExpressComments = 1
5095 BEGIN
5096 DELETE C
5097 FROM #Comment AS C
5098 INNER JOIN #Row AS R
5099 ON C.Comment_RecordID = R.RecordID
5100 WHERE R.SourceTypeID = 0
5101 END
5102
5103 -- Not showing when more than one comments
5104-- INSERT INTO [#Comment]
5105-- (
5106-- Comment_RecordID,
5107-- Comment
5108-- )
5109--
5110-- SELECT
5111-- C.Comment_RecordID,
5112-- (
5113-- SELECT C2.Comment + ', '
5114-- FROM [#Comment] AS C2 WITH(NOLOCK)
5115-- WHERE C2.Comment_RecordID = C.Comment_RecordID
5116-- GROUP BY C2.Comment
5117-- FOR XML PATH('')
5118-- )
5119-- FROM [#Comment] AS C WITH(NOLOCK)
5120-- WHERE DeleteFlg = 1
5121
5122 DELETE FROM [#Comment] WHERE DeleteFlg = 1
5123
5124 INSERT INTO #Comment(Comment_RecordID, Comment)
5125 SELECT DISTINCT
5126 R.RecordID,
5127 N.Note
5128 FROM [#Row] AS R
5129 INNER JOIN COService AS CS WITH(NOLOCK)
5130 ON R.COServiceID = CS.COServiceID
5131 INNER JOIN COrderNote AS N WITH(NOLOCK)
5132 ON N.COrderID = CS.COrderID
5133 END
5134
5135-- OK02082008=============================================================================================
5136 -- Load #COService
5137 -- =======================================================================================================
5138
5139 --PRINT 'Load COService'
5140
5141 IF @ProcessCOServices = 1
5142 BEGIN
5143
5144 /*NEW OR CHANGED Jeremy Dixon 1/2014*/
5145 INSERT INTO #CaptureLoadOrder
5146 ([Status]
5147 ,LoadNumber
5148 ,Mode)
5149 SELECT
5150 L.[Status]
5151 ,R.LoadNumber
5152 ,O.Mode
5153 FROM #Row AS R
5154 INNER JOIN SPOrder AS O WITH(NOLOCK)
5155 ON R.LoadNumber = O.LoadNumber
5156 AND O.LoadNumber > 0
5157 INNER JOIN [Load] L WITH(NOLOCK)
5158 ON O.LoadNumber = L.LoadNumber
5159 WHERE R.DisplayServiceFlg=1
5160
5161
5162 /* NEW OR CHANGED Seth Okoampa 4/10/2014
5163 Remove duplicated data inserted into #CaptureLoadOrder. Duplicates are going in there because of the Multiple
5164 modes per load in SPOrder table.
5165 */
5166 DELETE FROM CLO
5167 FROM #CaptureLoadOrder CLO
5168 INNER JOIN
5169 (
5170 SELECT DISTINCT LoadNumber FROM #CaptureLoadOrder GROUP BY LoadNumber HAVING COUNT(1) > 1
5171 )CLO2 ON CLO.LoadNumber = CLO2.LoadNumber AND CLO.Mode = 'Customs'
5172
5173
5174 /*NEW OR CHANGED Jeremy Dixon 11/2013*/
5175 INSERT INTO #COService_Capture
5176 (
5177 COService_RecordID,
5178 ActualMode,
5179 Expedited,
5180 ExpeditedReason,
5181 InboundStatus,
5182 FinancialCondition,
5183 NonConsolidationCharge,
5184 BaselineCharge,
5185 CHRStatus,
5186 RoutedShipments,
5187 ServiceLevel,
5188 Mode,
5189 OrderMode,
5190 LoadMode
5191 )
5192 SELECT DISTINCT
5193 R.RecordID AS COService_RecordID,
5194 C.Mode AS ActualMode,
5195 C.ExpeditedFlg AS Expedited,
5196 C.ExpeditedReason AS ExpeditedReason,
5197 C.[InboundStatus] AS InboundStatus,
5198 C.FinancialCondition AS FinancialCondition,
5199 0 AS NonConsolidationCharge,
5200 0 AS BaselineCharge,
5201 CASE
5202 WHEN (@SummarizeShipment = 1 AND R.MultiLegFlg = 1) THEN MLLoadStatus.DisplayStatus
5203 WHEN C.CustomerOrderNumber > 0 AND C.PooledFlg = 0 AND C.FirstLoadNumber > 0 THEN LoadStatus.DisplayStatus
5204 WHEN C.CustomerOrderNumber > 0 OR (@SummarizeShipment = 0 AND R.MultiLegFlg = 1) THEN ISNULL(OrderStatus.DisplayStatus, DS.OrderStatus)
5205ELSE LoadStatus.DisplayStatus
5206 END AS CHRStatus,
5207 CASE
5208 WHEN ISNULL(C.OMSRouting, 0) = 0 THEN 'CHR'
5209 ELSE 'Non-CHR'
5210 END AS RoutedShipments,
5211 ISNULL(RD.[Value], C.ServiceLevel) AS ServiceLevel,
5212 CASE
5213 WHEN @HideMode = 1 THEN 'Service Level'
5214 WHEN @SummarizeShipment = 1 AND MultiLegFlg = 1 THEN L.Mode
5215 ELSE C.Mode
5216 END AS Mode,
5217 C.Mode AS OrderMode,
5218 L.Mode AS LoadMode
5219 FROM [#Row] AS R
5220 INNER JOIN COService AS C WITH(NOLOCK)
5221 ON R.COServiceID = C.COServiceID
5222 INNER JOIN NTSR.dbo.DimStatus AS DS WITH(NOLOCK)
5223 ON C.KeyStatusID = DS.KeyStatusID
5224 LEFT OUTER JOIN MDMPublicReadOnly.ref.RefData AS RD WITH(NOLOCK)
5225 ON C.ServiceLevel = RD.RefDataCode AND RD.RefDataCategoryCode = 'ModePrimaryServiceLevel'
5226 LEFT OUTER JOIN CHRWOnline.dbo.UT_StatusMappingItem AS OrderStatus WITH(NOLOCK)
5227 ON DS.OrderStatus = OrderStatus.SourceSystemStatus
5228 AND OrderStatus.StatusMappingID = @StatusMappingID
5229 AND OrderStatus.SourceSystem = 1 --OMS
5230 LEFT OUTER JOIN CHRWOnline.dbo.UT_StatusMappingItem AS LoadStatus WITH(NOLOCK)
5231 ON DS.LoadStatus = LoadStatus.SourceSystemStatus
5232 AND LoadStatus.StatusMappingID = @StatusMappingID
5233 AND LoadStatus.SourceSystem = 2 --Express
5234 /*NEW OR CHANGED Jeremy Dixon 1/2014*/
5235 -- LEFT OUTER JOIN SPOrder AS O WITH(NOLOCK)
5236 --ON R.LoadNumber = O.LoadNumber AND O.LoadNumber > 0
5237 -- LEFT OUTER JOIN [Load] L WITH(NOLOCK)
5238 --ON O.LoadNumber = L.LoadNumber
5239 LEFT OUTER JOIN #CaptureLoadOrder AS L
5240 ON L.LoadNumber = R.LoadNumber
5241 LEFT OUTER JOIN NTSR.dbo.DimStatus DSL WITH(NOLOCK)
5242 ON CAST(LTRIM(RTRIM(L.[Status])) AS VARCHAR(10)) + '|-1' = DSL.KeyStatusNK
5243 LEFT OUTER JOIN CHRWOnline.dbo.UT_StatusMappingItem AS MLLoadStatus WITH(NOLOCK)
5244 ON DSL.LoadStatus = MLLoadStatus.SourceSystemStatus
5245 AND MLLoadStatus.StatusMappingID = @StatusMappingID
5246 AND MLLoadStatus.SourceSystem = 2
5247 WHERE R.DisplayServiceFlg=1
5248
5249 INSERT INTO #COService
5250 (
5251 COService_RecordID,
5252 ActualMode,
5253 Expedited,
5254 ExpeditedReason,
5255 InboundStatus,
5256 FinancialCondition,
5257 NonConsolidationCharge,
5258 BaselineCharge,
5259 CHRStatus,
5260 RoutedShipments,
5261 ServiceLevel,
5262 Mode,
5263 OrderMode,
5264 LoadMode
5265 )
5266 SELECT
5267 R.COService_RecordID,
5268 R.ActualMode,
5269 R.Expedited,
5270 R.ExpeditedReason,
5271 R.InboundStatus,
5272 R.FinancialCondition,
5273 S.SumCurrentCharge AS NonConsolidationCharge,
5274 S.SumBaselineCharge AS BaselineCharge,
5275 R.CHRStatus,
5276 R.RoutedShipments,
5277 R.ServiceLevel,
5278 R.Mode,
5279 R.OrderMode,
5280 R.LoadMode
5281 FROM #COService_Capture AS R
5282 CROSS APPLY
5283 (
5284 SELECT SUM(ISNULL(C2.CurrentCharge, 0)), SUM(ISNULL(C2.BaselineCharge, 0))
5285 FROM #Row AS R2
5286 INNER JOIN dbo.COService AS C2 WITH(NOLOCK)
5287 ON R2.COServiceID = C2.COServiceID
5288 WHERE R.COService_RecordID = R2.RecordID
5289 GROUP BY R2.RecordID
5290 ) S(SumCurrentCharge, SumBaselineCharge)
5291
5292 IF @SummarizeShipment = 0 AND EXISTS(SELECT TOP 1 1 FROM #Row WHERE MultiLegFlg = 1)
5293 BEGIN
5294 UPDATE #COService
5295 SET LoadMode = STUFF(
5296 (
5297 SELECT DISTINCT
5298 ',' + CAST(O.Mode AS VARCHAR(32))
5299 FROM #Row M
5300 INNER JOIN dbo.COService AS CS WITH(NOLOCK) ON M.CustomerOrderNumber = CS.CustomerOrderNumber
5301 INNER JOIN dbo.Activity AS A WITH(NOLOCK) ON CS.COServiceID = A.COServiceID
5302 INNER JOIN dbo.SPOrder AS O WITH(NOLOCK) ON A.SPOrderID = O.SPOrderID
5303 WHERE M.CustomerOrderNumber = R2.CustomerOrderNumber AND O.LoadNumber > 0 AND O.LoadNumber IS NOT NULL AND M.MultiLegFlg = 1
5304 FOR XML PATH(''), TYPE).value('.', 'VARCHAR(512)'
5305 ), 1, 1, ''
5306 )
5307 FROM #COService R
5308 INNER JOIN #Row R2 ON R.COService_RecordId = R2.RecordID
5309 WHERE R2.MultiLegFlg = 1
5310 END
5311
5312
5313 -- Do the spoofed status updating
5314 IF @SpoofBookedStatus = 1 AND OBJECT_ID('tempdb..#SpoofStatus') IS NOT NULL BEGIN
5315 UPDATE tmp_C SET CHRStatus = 'Booked'
5316 FROM #COService AS tmp_C WITH(NOLOCK)
5317 INNER JOIN #Row AS R WITH(NOLOCK)
5318 ON tmp_C.COService_RecordID = R.RecordID
5319 INNER JOIN COService AS C WITH(NOLOCK)
5320 ON R.COServiceID = C.COServiceID
5321 INNER JOIN NTSR.dbo.DimStatus AS DS WITH(NOLOCK)
5322 ON C.KeyStatusID = DS.KeyStatusID
5323 LEFT JOIN #SpoofStatus AS Spoofed WITH(NOLOCK)
5324 ON C.KeyStatusID = Spoofed.StatusID
5325 LEFT OUTER JOIN CHRWOnline.dbo.UT_StatusMappingItem AS LoadStatus WITH(NOLOCK)
5326 ON DS.LoadStatus = LoadStatus.SourceSystemStatus
5327 AND LoadStatus.StatusMappingID = @StatusMappingID
5328 AND LoadStatus.SourceSystem = 2
5329 WHERE
5330 Spoofed.StatusID IS NOT NULL AND
5331 LoadStatus.DisplayStatus = 'Ordered' AND
5332 R.LogisticFlg = 0
5333 END
5334
5335 END
5336
5337 IF @ProcessCompliance = 1
5338 BEGIN
5339 INSERT INTO #Compliance
5340 (
5341 Compliance_RecordID,
5342 NonComplianceCode,
5343 NonComplianceCodeReason
5344 )
5345 SELECT DISTINCT
5346 R.RecordID,
5347 'Non-compliant',
5348 C.NonComplianceCode
5349 FROM #Row AS R
5350 INNER JOIN COService AS C WITH (NOLOCK)
5351 ON R.COServiceID = C.COServiceID
5352 WHERE C.ComplianceFlg = 0
5353
5354 -- records with multiple reasons:
5355 UPDATE C SET
5356 DeleteFlg = 1
5357 FROM #Compliance AS C
5358 WHERE EXISTS (SELECT 1 FROM #Compliance AS C2
5359 WHERE C2.Compliance_RecordID = C.Compliance_RecordID
5360 GROUP BY C2.Compliance_RecordID
5361 HAVING COUNT(1) > 1)
5362
5363 INSERT INTO #Compliance
5364 (
5365 Compliance_RecordID,
5366 NonComplianceCode,
5367 NonComplianceCodeReason
5368 )
5369 SELECT DISTINCT
5370 Compliance_RecordID,
5371 NonComplianceCode,
5372 'Multiple'
5373 FROM #Compliance
5374 WHERE DeleteFlg = 1
5375
5376 DELETE FROM #Compliance WHERE DeleteFlg = 1
5377
5378 -- ensure we have a record for compliant records
5379 -- that aren't part of a summary shipment that already
5380 -- inserted a record because one of the legs (orders)
5381 -- was non-compliant:
5382 INSERT INTO #Compliance
5383 (
5384 Compliance_RecordID,
5385 NonComplianceCode,
5386 NonComplianceCodeReason
5387 )
5388 SELECT
5389 R.RecordID,
5390 'Compliant',
5391 ''
5392 FROM #Row AS R
5393 INNER JOIN COService AS C WITH (NOLOCK)
5394 ON R.COServiceID = C.COServiceID
5395 LEFT OUTER JOIN #Compliance AS C2
5396 ON C2.Compliance_RecordID = R.RecordID
5397 WHERE C.ComplianceFlg = 1 AND C2.Compliance_RecordID IS NULL
5398 END
5399
5400 -- OK02112008=============================================================================================
5401 -- Load #LastInvoice
5402 -- =======================================================================================================
5403
5404 --PRINT 'Load LastInvoice'
5405
5406 IF @ProcessLastInvoices = 1
5407 BEGIN
5408 -- Insert all invoices that have been invoiced
5409 INSERT INTO #LastInvoice(LastInvoice_RecordID, Invoiced, LastInvoiceDate)
5410 SELECT
5411 R.RecordID AS LastInvoice_RecordID,
5412 1 AS Invoiced,
5413 MAX(OID.DateValue) AS LastInvoiceDate
5414 FROM [#Row] AS R
5415 INNER JOIN COServiceInvoice AS I WITH(NOLOCK)
5416 ON R.COServiceID = I.COServiceID
5417 INNER JOIN OrderInvoice AS OI WITH(NOLOCK)
5418 ON I.OrderInvoiceID = OI.OrderInvoiceID
5419 INNER JOIN OrderInvoiceDate AS OID WITH (NOLOCK)
5420 ON OID.OrderInvoiceID = OI.OrderInvoiceID
5421 AND OID.DateType = 'Invoice Date'
5422 INNER JOIN OrderInvoiceParty AS OIP WITH(NOLOCK)
5423 ON OI.OrderInvoiceID = OIP.OrderInvoiceID
5424 INNER JOIN OrderParty AS OP WITH(NOLOCK)
5425 ON OIP.OrderPartyID = OP.OrderPartyID AND OP.[Role] = 'BILLTO'
5426 INNER JOIN #UserCCodes AS CC
5427 ON OP.PartyCode = CC.CompanyCode
5428 GROUP BY R.RecordID
5429 OPTION(LOOP JOIN)
5430
5431 END
5432
5433 -- OK02112008===================================================================================
5434 -- Load #LastEvent
5435 -- =============================================================================================
5436
5437 --PRINT 'Load LastEvent'
5438
5439 IF @ProcessLastEvents = 1
5440 BEGIN
5441 -- 09/16/2008 GANASAD Added City, State, Country
5442 INSERT INTO #LastEvent(LastEvent_RecordID, LastEvent)
5443 SELECT
5444 R.RecordID,
5445 CASE
5446 WHEN ISNULL(D.City, '') = '' AND ISNULL(D.State, '') = '' THEN
5447 SUBSTRING(MAX(ISNULL(D.Note, '')), 1, 500)
5448 ELSE
5449 SUBSTRING(MAX(ISNULL(D.Note, '') + ' at ' + ISNULL(D.City, '' ) + ', ' + ISNULL(D.State, '') ), 1, 500)
5450 END
5451 FROM [#Row] AS R
5452 INNER JOIN Activity AS A WITH(NOLOCK)
5453 ON R.COServiceID = A.COServiceID
5454 INNER JOIN DriverLog AS D WITH(NOLOCK)
5455 ON A.SPOrderID = D.SPOrderID AND D.DriverLogID =
5456 (
5457 SELECT TOP 1
5458 D2.DriverLogID
5459 FROM
5460 [#Row] AS R2 WITH(NOLOCK)
5461 INNER JOIN
5462 Activity AS A2 WITH(NOLOCK)
5463 ON R2.COServiceID = A2.COServiceID
5464 INNER JOIN
5465 DriverLog AS D2 WITH(NOLOCK)
5466 ON A2.SPOrderID = D2.SPOrderID
5467 LEFT OUTER JOIN
5468 CHRWOnline.dbo.Filter AS F WITH(NOLOCK)
5469 ON F.Name = 'InformationFrom'
5470 AND D2.InformationFrom = F.Value
5471 AND F.ShouldExclude = 1
5472 LEFT OUTER JOIN
5473 CHRWOnline.dbo.Filter AS F2 WITH(NOLOCK)
5474 ON F2.Name = 'EnteredBy'
5475 AND D2.EnteredBy = F2.Value
5476 AND F2.ShouldExclude = 1
5477 WHERE
5478 R2.RecordID = R.RecordID AND
5479 D2.Note IS NOT NULL AND
5480 NOT (F.FilterID IS NOT NULL AND F2.FilterID IS NOT NULL)
5481 ORDER BY
5482 D2.EventDate DESC
5483 )
5484
5485 GROUP BY R.RecordID,D.City,D.State
5486 END
5487
5488 -- =============================================================================================
5489 -- Load #LastIMDLEvent
5490 -- =============================================================================================
5491
5492 --PRINT 'Load LastIMDLEvent'
5493 -- 04/15/2008 GANASAD
5494 IF @ProcessLastIMDLEvents = 1
5495 BEGIN
5496 /*<><><><><><><>Jeremy Dixon change 12/11/2013<><><><><><><>*/
5497
5498INSERT INTO #WantedBookTypes
5499 (BookType)
5500 SELECT 'IPU' UNION ALL
5501 SELECT 'ILH' UNION ALL
5502 SELECT 'IXT' UNION ALL
5503 SELECT 'IDL'
5504
5505/*<><><><><><><>Jeremy Dixon change 12/11/2013<><><><><><><>*/
5506INSERT INTO #LASTIMDEventStage
5507 (RecordID
5508 ,Note
5509 ,City
5510 ,[State]
5511 ,SPOrderID
5512 ,EventDate)
5513SELECT R.RecordID, D.Note, D.City, D.[State], A.SPOrderID, D.EventDate
5514 FROM [#Row] AS R WITH(NOLOCK)
5515 INNER JOIN Activity AS A WITH(NOLOCK)
5516 ON R.COServiceID = A.COServiceID
5517 INNER JOIN SPOrder AS O WITH(NOLOCK)
5518 ON A.SPOrderID = O.SPOrderID
5519 INNER JOIN #WantedBookTypes AS WBT WITH(NOLOCK)
5520 ON O.BookType = WBT.BookType
5521 INNER JOIN DriverLog AS D WITH(NOLOCK)
5522 ON A.SPOrderID = D.SPOrderID
5523
5524/*<><><><><><><>Jeremy Dixon change 12/11/2013<><><><><><><>*/
5525 INSERT INTO [#LastIMDLEvent]
5526 (
5527 LastIMDLEvent_RecordID,
5528 LastIMDLEvent
5529 )
5530 SELECT
5531 D.RecordID,
5532 CASE
5533 WHEN ISNULL(D.City, '') = '' AND ISNULL(D.State, '') = '' THEN
5534 SUBSTRING(MAX(ISNULL(D.Note, '')), 1, 500)
5535 ELSE
5536 SUBSTRING(MAX(ISNULL(D.Note, '') + ' at ' + ISNULL(D.City, '' ) + ', ' + ISNULL(D.State, '') ), 1, 500)
5537 END
5538 FROM #LASTIMDEventStage AS D
5539 WHERE D.EventDate =
5540 (
5541 SELECT MAX(ISNULL(D2.EventDate, 0))
5542 FROM [#Row] AS R2
5543 INNER JOIN Activity AS A2 WITH(NOLOCK)
5544 ON R2.COServiceID = A2.COServiceID
5545 INNER JOIN SPOrder AS O WITH(NOLOCK)
5546 ON D.SPOrderID = O.SPOrderID
5547 INNER JOIN #WantedBookTypes AS WBT WITH(NOLOCK)
5548 ON O.BookType = WBT.BookType
5549 INNER JOIN DriverLog AS D2 WITH(NOLOCK)
5550 ON A2.SPOrderID = D2.SPOrderID
5551 WHERE R2.RecordID = D.RecordID AND D2.Note IS NOT NULL
5552 )
5553
5554 GROUP BY D.RecordID,D.City,D.State
5555
5556 END
5557
5558 -- OK02112008===================================================================================
5559 -- Load #SPOrder
5560 -- =============================================================================================
5561
5562 IF @ProcessSPOrders = 1
5563 BEGIN
5564 --PRINT 'Load SPOrder'
5565
5566 INSERT INTO #SPOrder
5567 (
5568 SPOrder_RecordID
5569 ,Conveyance
5570 ,ContractNum
5571 ,BookingNum
5572 ,BookingDate
5573 ,CarrierName
5574 ,EquipmentType
5575 ,TractorNum
5576 ,TrailerNum
5577 ,TrailerSize
5578 ,AirLineCarrier
5579 ,FlightNumber
5580 )
5581
5582 SELECT DISTINCT
5583 R.RecordID AS SPOrder_RecordID,
5584ISNULL(O.Vessel, '') +
5585 ISNULL('/' + NULLIF(LTRIM(RTRIM(O.Voyage)), ''), '') AS Conveyance,
5586 O.ContractNumber AS ContractNum,
5587 O.BookingNumber AS BookingNum,
5588 CASE
5589 WHEN L.InternationalFlg = 1 THEN ISPOD.DateValue
5590 ELSE SPOD.DateValue
5591 END AS BookingDate,
5592 CASE
5593 WHEN R.IntlCHRRole = 'N' THEN 'Christal Lines'
5594 ELSE OP.[Name]
5595 END AS CarrierName,
5596 CASE
5597 WHEN L.InternationalFlg = 0 THEN ISNULL(NULLIF(O.EquipmentType, ''), L.EquipmentType)
5598 ELSE ''
5599 END AS EquipmentType,
5600 O.TractorNumber AS TractorNum,
5601 O.TrailerNumber AS TrailerNum,
5602 CASE
5603 WHEN L.InternationalFlg = 0 THEN CAST(O.EquipmentSize AS VARCHAR(500))
5604 ELSE ''
5605 END AS TrailerSize,
5606 O.Vessel AS AirLineCarrier,
5607 O.Voyage AS FlightNumber
5608 FROM [#Row] AS R
5609 INNER JOIN Activity AS A WITH(NOLOCK)
5610 ON R.COServiceID = A.COServiceID
5611 INNER JOIN SPOrder AS O WITH(NOLOCK)
5612 ON A.SPOrderID = O.SPOrderID AND O.BookType <> 'V' AND ISNULL(O.ShipmentType,'H') = 'H'
5613 LEFT OUTER JOIN SPOParty AS SP WITH(NOLOCK)
5614 ON O.SPOrderID = SP.SPOrderID
5615 LEFT OUTER JOIN SPOrderDate AS SPOD WITH(NOLOCK)
5616 ON SP.SPOrderID = SPOD.SPOrderID AND SPOD.DateType='Booked Date'
5617 LEFT OUTER JOIN SPOrderDate AS ISPOD WITH (NOLOCK)
5618 ON SP.SPOrderID = ISPOD.SPOrderID AND ISPOD.DateType = 'INTL Booked Date'
5619
5620 LEFT OUTER JOIN [Load] as L WITH(NOLOCK)
5621 ON
5622 O.LoadNumber = L.LoadNumber
5623 AND O.SourceTypeID = L.SourceTypeID
5624 AND O.PlannedLoad = L.PlannedLoadNumber
5625
5626 LEFT OUTER JOIN OrderParty AS OP WITH(NOLOCK)
5627 ON SP.OrderPartyID = OP.OrderPartyID AND [Role] = 'CARRIER'
5628WHERE R.LoadNumber > 0
5629
5630 UNION
5631
5632 SELECT DISTINCT
5633 R.RecordID AS SPOrder_RecordID,
5634ISNULL(O.Vessel, '') +
5635 ISNULL('/' + NULLIF(LTRIM(RTRIM(O.Voyage)), ''), '') AS Conveyance,
5636 O.ContractNumber AS ContractNum,
5637 O.BookingNumber AS BookingNum,
5638 SPOD.DateValue AS BookingDate,
5639 CASE
5640 WHEN R.IntlCHRRole = 'N' THEN 'Christal Lines'
5641 ELSE OP.[Name]
5642 END AS CarrierName,
5643 '' AS EquipmentType,
5644 O.TractorNumber AS TractorNum,
5645 O.TrailerNumber AS TrailerNum,
5646 '' AS TrailerSize,
5647 O.Vessel AS AirLineCarrier,
5648 O.Voyage AS FlightNumber
5649 FROM [#Row] AS R
5650 INNER JOIN Activity AS A WITH(NOLOCK)
5651 ON R.COServiceID = A.COServiceID
5652 INNER JOIN SPOrder AS O WITH(NOLOCK)
5653 ON A.SPOrderID = O.SPOrderID AND O.BookType <> 'V' AND ISNULL(O.ShipmentType,'H') = 'H'
5654 LEFT OUTER JOIN SPOParty AS SP WITH(NOLOCK)
5655 ON O.SPOrderID = SP.SPOrderID
5656 LEFT OUTER JOIN SPOrderDate AS SPOD WITH(NOLOCK)
5657 ON SP.SPOrderID = SPOD.SPOrderID AND SPOD.DateType='Booked Date'
5658 LEFT OUTER JOIN SPOrderDate AS ISPOD WITH (NOLOCK)
5659 ON SP.SPOrderID = ISPOD.SPOrderID AND ISPOD.DateType = 'INTL Booked Date'
5660 LEFT OUTER JOIN OrderParty AS OP WITH(NOLOCK)
5661 ON SP.OrderPartyID = OP.OrderPartyID AND [Role] = 'CARRIER'
5662 WHERE R.SourceTypeID = 7 AND R.LoadNumber = -1
5663
5664 -- Delete records that have multiple records per record id;
5665 -- We're going to summarize them in step 3.
5666 --PRINT 'Update SPOrder DeletFlg'
5667
5668 UPDATE S
5669 SET DeleteFlg = 1
5670 FROM #SPOrder AS S
5671 WHERE EXISTS
5672 (
5673 SELECT S2.SPOrder_RecordID
5674 FROM #SPOrder AS S2
5675 WHERE S.SPOrder_RecordID = S2.SPOrder_RecordID
5676 GROUP BY S2.SPOrder_RecordID
5677 HAVING COUNT(1) > 1
5678 )
5679
5680/*NEW OR CHANGED Jeremy Dixon 1/2014*/
5681 INSERT INTO #Conveyance
5682 (SPOrder_RecordID
5683 ,Conveyance)
5684 SELECT SPOrder_RecordID
5685 ,Conveyance
5686 FROM #SPOrder AS SPO
5687 WHERE SPO.DeleteFlg = 1
5688
5689/*NEW OR CHANGED Jeremy Dixon 1/2014*/
5690 INSERT INTO #ContractNum
5691 (SPOrder_RecordID
5692 ,ContractNum)
5693 SELECT SPOrder_RecordID
5694 ,ContractNum
5695 FROM #SPOrder AS SPO
5696 WHERE SPO.DeleteFlg = 1
5697
5698/*NEW OR CHANGED Jeremy Dixon 1/2014*/
5699 INSERT INTO #CarrierName
5700 (SPOrder_RecordID
5701 ,CarrierName)
5702 SELECT SPOrder_RecordID
5703 ,CarrierName
5704 FROM #SPOrder AS SPO
5705 WHERE SPO.DeleteFlg = 1
5706
5707/*NEW OR CHANGED Jeremy Dixon 1/2014*/
5708 INSERT INTO #BookingNum
5709 (SPOrder_RecordID
5710 ,BookingNum)
5711 SELECT SPOrder_RecordID
5712 ,BookingNum
5713 FROM #SPOrder AS SPO
5714 WHERE SPO.DeleteFlg = 1
5715
5716/*NEW OR CHANGED Jeremy Dixon 1/2014*/
5717 INSERT INTO #EquipmentType
5718 (SPOrder_RecordID
5719 ,EquipmentType)
5720 SELECT SPOrder_RecordID
5721 ,EquipmentType
5722 FROM #SPOrder AS SPO
5723 WHERE SPO.DeleteFlg = 1
5724
5725/*NEW OR CHANGED Jeremy Dixon 1/2014*/
5726 INSERT INTO #TractorNum
5727 (SPOrder_RecordID
5728 ,TractorNum)
5729 SELECT SPOrder_RecordID
5730 ,TractorNum
5731 FROM #SPOrder AS SPO
5732 WHERE SPO.DeleteFlg = 1
5733
5734/*NEW OR CHANGED Jeremy Dixon 1/2014*/
5735 INSERT INTO #TrailerNum
5736 (SPOrder_RecordID
5737 ,TrailerNum)
5738 SELECT SPOrder_RecordID
5739 ,TrailerNum
5740 FROM #SPOrder AS SPO
5741 WHERE SPO.DeleteFlg = 1
5742
5743/*NEW OR CHANGED Jeremy Dixon 1/2014*/
5744 INSERT INTO #TrailerSize
5745 (SPOrder_RecordID
5746 ,TrailerSize)
5747 SELECT SPOrder_RecordID
5748 ,TrailerSize
5749 FROM #SPOrder AS SPO
5750 WHERE SPO.DeleteFlg = 1
5751
5752/*NEW OR CHANGED Jeremy Dixon 1/2014*/
5753 INSERT INTO #AirLineCarrier
5754 (SPOrder_RecordID
5755 ,AirLineCarrier)
5756 SELECT SPOrder_RecordID
5757 ,AirLineCarrier
5758 FROM #SPOrder AS SPO
5759 WHERE SPO.DeleteFlg = 1
5760
5761/*NEW OR CHANGED Jeremy Dixon 1/2014*/
5762 INSERT INTO #FlightNumber
5763 (SPOrder_RecordID
5764 ,FlightNumber)
5765 SELECT SPOrder_RecordID
5766 ,FlightNumber
5767 FROM #SPOrder AS SPO
5768 WHERE SPO.DeleteFlg = 1
5769
5770
5771/*NEW OR CHANGED Jeremy Dixon 1/2014*/
5772-- --PRINT 'Load SPOrder .Count(1) > 1 '
5773INSERT INTO #SPOrder
5774(
5775 SPOrder_RecordID
5776 ,Conveyance
5777 ,ContractNum
5778 ,BookingNum
5779 ,BookingDate
5780 ,CarrierName
5781 ,EquipmentType
5782 ,TractorNum
5783 ,TrailerNum
5784 ,TrailerSize
5785 ,AirLineCarrier
5786 ,FlightNumber
5787)
5788SELECT
5789 SPO.SPOrder_RecordID AS SPOrder_RecordID,
5790 (
5791 SELECT RTRIM(SPO2.Conveyance) + ', '
5792 FROM #Conveyance AS SPO2
5793 WHERE
5794 SPO2.SPOrder_RecordID = SPO.SPOrder_RecordID
5795 AND NULLIF(RTRIM(SPO2.Conveyance), '')
5796 IS NOT NULL
5797 GROUP BY SPO2.Conveyance
5798 FOR XML PATH('')
5799 ) AS Conveyance,
5800 (
5801 SELECT RTRIM(SPO2.ContractNum) + ', '
5802 FROM #ContractNum AS SPO2
5803 WHERE
5804 SPO2.SPOrder_RecordID =
5805 SPO.SPOrder_RecordID
5806 AND NULLIF(RTRIM(SPO2.ContractNum), '')
5807 IS NOT NULL
5808 GROUP BY SPO2.ContractNum
5809 FOR XML PATH('')
5810 ) AS ContractNum,
5811
5812 (
5813 SELECT RTRIM(SPO2.BookingNum) + ', '
5814 FROM #BookingNum AS SPO2
5815 WHERE
5816 SPO2.SPOrder_RecordID =
5817 SPO.SPOrder_RecordID
5818 AND NULLIF(RTRIM(SPO2.BookingNum), '')
5819 IS NOT NULL
5820 GROUP BY SPO2.BookingNum
5821 FOR XML PATH('')
5822 ) AS BookingNum,
5823
5824 -- We looked at this modification yesterday for the NULL
5825 -- aggregate problem but never modified the procedure.
5826 NULLIF(MIN(ISNULL(SPO.BookingDate, 99990101)), 99990101) AS BookingDate,
5827
5828 (
5829 SELECT RTRIM(SPO2.CarrierName) + ', '
5830 FROM #CarrierName AS SPO2
5831 WHERE
5832 SPO2.SPOrder_RecordID =
5833 SPO.SPOrder_RecordID
5834 AND NULLIF(RTRIM(SPO2.CarrierName), '')
5835 IS NOT NULL
5836 GROUP BY SPO2.CarrierName
5837 FOR XML PATH(''), ROOT('CarrierName'),TYPE
5838 ).value('/CarrierName[1]','varchar(max)') AS CarrierName,
5839
5840 (
5841 SELECT RTRIM(SPO2.EquipmentType) + ', '
5842 FROM #EquipmentType AS SPO2
5843 WHERE
5844 SPO2.SPOrder_RecordID =
5845 SPO.SPOrder_RecordID
5846 AND NULLIF(RTRIM(SPO2.EquipmentType), '')
5847 IS NOT NULL
5848 GROUP BY SPO2.EquipmentType
5849 FOR XML PATH('')
5850 ) AS EquipmentType,
5851
5852 (
5853 SELECT RTRIM(SPO2.TractorNum) + ', '
5854 FROM #TractorNum AS SPO2
5855 WHERE
5856 SPO2.SPOrder_RecordID =
5857 SPO.SPOrder_RecordID
5858 AND NULLIF(RTRIM(SPO2.TractorNum), '')
5859 IS NOT NULL
5860 GROUP BY SPO2.TractorNum
5861 FOR XML PATH('')
5862 ) AS TractorNum,
5863
5864 (
5865 SELECT RTRIM(SPO2.TrailerNum) + ', '
5866 FROM #TrailerNum AS SPO2
5867 WHERE
5868 SPO2.SPOrder_RecordID =
5869 SPO.SPOrder_RecordID
5870 AND NULLIF(RTRIM(SPO2.TrailerNum), '')
5871 IS NOT NULL
5872 GROUP BY SPO2.TrailerNum
5873 FOR XML PATH('')
5874 ) AS TrailerNum,
5875
5876 (
5877 SELECT RTRIM(CAST(
5878 SPO2.TrailerSize AS VARCHAR(20))) + ', '
5879 FROM #TrailerSize AS SPO2
5880 WHERE
5881 SPO2.SPOrder_RecordID =
5882 SPO.SPOrder_RecordID
5883 AND NULLIF(RTRIM(SPO2.TrailerSize), '')
5884 IS NOT NULL
5885 GROUP BY SPO2.TrailerSize
5886 FOR XML PATH('')
5887 ) AS TrailerSize,
5888 (
5889 SELECT RTRIM(SPO2.AirLineCarrier) + ', '
5890 FROM #AirLineCarrier AS SPO2
5891 WHERE
5892 SPO2.SPOrder_RecordID =
5893 SPO.SPOrder_RecordID
5894 AND NULLIF(RTRIM(SPO2.AirLineCarrier), '')
5895 IS NOT NULL
5896 GROUP BY SPO2.AirLineCarrier
5897 FOR XML PATH('')
5898 ) AS AirLineCarrier,
5899 (
5900 SELECT RTRIM(SPO2.FlightNumber) + ', '
5901 FROM #FlightNumber AS SPO2 WITH(NOLOCK)
5902 WHERE
5903 SPO2.SPOrder_RecordID =
5904 SPO.SPOrder_RecordID
5905 AND NULLIF(RTRIM(SPO2.FlightNumber), '')
5906 IS NOT NULL
5907 GROUP BY SPO2.FlightNumber
5908 FOR XML PATH('')
5909 ) AS FlightNumber
5910 FROM #SPOrder AS SPO
5911 WHERE SPO.DeleteFlg = 1
5912 GROUP BY SPO.SPOrder_RecordID
5913
5914
5915 --PRINT 'Delete from SPOrder '
5916 DELETE
5917 FROM #SPOrder
5918 WHERE DeleteFlg = 1
5919
5920END
5921
5922 -- =============================================================================================
5923 -- Load #SPOrderIntl
5924 -- =============================================================================================
5925
5926IF @ProcessSPOrderIntls = 1
5927BEGIN
5928 --PRINT 'LOAD SPOrderIntl'
5929 INSERT INTO #SPOrderIntl
5930 (
5931 SPOrderIntl_RecordID
5932 ,ContainerNumber
5933 ,ContainerType
5934 ,SummContainerNumber
5935 ,SummContainerType
5936 )
5937 SELECT DISTINCT
5938 R.RecordID AS SPOrder_RecordID,
5939 CASE
5940 WHEN (CO.IsNavPOOrder = 1 OR CO.IsNavPOShipment = 1) AND ISNULL(CO.POVerifyFlg,1) = 0 THEN ''
5941 ELSE CS.ContainerNumber
5942 END AS ContainerNumber,
5943 CASE
5944 WHEN (CO.IsNavPOOrder = 1 OR CO.IsNavPOShipment = 1) AND ISNULL(CO.POVerifyFlg,1) = 0 THEN ''
5945 ELSE CS.ContainerType
5946 END AS ContainerType,
5947 COSG.ContainerNumber AS SummContainerNumber,
5948 CASE
5949 WHEN R.CustomerOrderNumber < 0 THEN COSG.ContainerType
5950 ELSE NULL
5951 END AS SummContainerType
5952 FROM [#Row] AS R
5953 INNER JOIN COService AS CS WITH (NOLOCK)
5954 ON R.COServiceID = CS.COServiceID
5955 LEFT JOIN COrder AS CO WITH (NOLOCK)
5956 ON CO.COrderID = R.COrderID
5957 LEFT OUTER JOIN COSGroup AS COSG WITH (NOLOCK)
5958 ON COSG.COSGroupID = CS.COSGroupID
5959 AND @SummarizeOcean = 1
5960
5961 -- Delete records that have multiple records per record id;
5962 -- We're going to summarize them in step 3.
5963 --PRINT 'Update SPOrderIntl DeletFlg'
5964
5965 UPDATE S
5966 SET DeleteFlg = 1
5967 FROM #SPOrderIntl AS S
5968 WHERE EXISTS
5969 (
5970 SELECT S2.SPOrderIntl_RecordID
5971 FROM #SPOrderIntl AS S2
5972 WHERE S.SPOrderIntl_RecordID = S2.SPOrderIntl_RecordID
5973 GROUP BY S2.SPOrderIntl_RecordID
5974 HAVING COUNT(1) > 1
5975 )
5976
5977 -- Added this b/c sorting was taking about 30% of the time.
5978 -- Sorting for ContainerType still exists and is taking about
5979 -- 97% of the time.
5980 -- Pulled this up to when the table was created for performance
5981 --CREATE CLUSTERED INDEX INX_SPorderIntl_ContainerNumber ON #SPOrderIntl(SPOrderIntl_RecordID, ContainerNumber)
5982
5983 --PRINT 'Load SPOrderIntl.Count(1) > 1 '
5984 INSERT INTO #SPOrderIntl
5985 (
5986 SPOrderIntl_RecordID
5987 ,ContainerNumber
5988 ,ContainerType
5989 )
5990 SELECT
5991 SPO.SPOrderIntl_RecordID AS SPOrderIntl_RecordID,
5992 ISNULL(SPO.SummContainerNumber,
5993 (
5994 SELECT RTRIM(SPO2.ContainerNumber) + ', '
5995 FROM #SPOrderIntl AS SPO2
5996 WHERE
5997 SPO2.SPOrderIntl_RecordID = SPO.SPOrderIntl_RecordID
5998 AND NULLIF(RTRIM(SPO2.ContainerNumber), '')
5999 IS NOT NULL
6000 GROUP BY SPO2.ContainerNumber
6001 FOR XML PATH('')
6002 )
6003 ) AS ContainerNumber,
6004 ISNULL(SPO.SummContainerType,
6005 (
6006 SELECT RTRIM(SPO2.ContainerType) + ', '
6007 FROM #SPOrderIntl AS SPO2
6008 WHERE
6009 SPO2.SPOrderIntl_RecordID = SPO.SPOrderIntl_RecordID
6010 AND NULLIF(RTRIM(SPO2.ContainerType), '')
6011 IS NOT NULL
6012 GROUP BY SPO2.ContainerType
6013 FOR XML PATH('')
6014 )
6015 ) AS ContainerType
6016
6017 FROM #SPOrderIntl AS SPO
6018 WHERE SPO.DeleteFlg = 1
6019 GROUP BY SPO.SPOrderIntl_RecordID,SPO.SummContainerNumber,SPO.SummContainerType
6020
6021 --PRINT 'Delete from SPOrderIntl '
6022 DELETE
6023 FROM #SPOrderIntl
6024 WHERE DeleteFlg = 1
6025END
6026
6027 -- OK02122008===================================================================================
6028 -- Load #SPOrderOther
6029 -- =============================================================================================
6030
6031 --PRINT 'Load SPOrderOther'
6032
6033 IF @ProcessSPOrderOthers = 1
6034 BEGIN
6035 INSERT INTO [#SPOrderOther]
6036 (
6037 SPOrderOther_RecordID,
6038 DeliveryCarrierName,
6039 TenderedToCarrierName
6040 )
6041
6042 SELECT DISTINCT
6043 R.RecordID,
6044 PDel.[Name],
6045 PDis.[Name]
6046 FROM [#Row] AS R
6047 INNER JOIN COService AS S WITH(NOLOCK)
6048 ON R.COServiceID = S.COServiceID
6049 INNER JOIN COrder AS C WITH(NOLOCK)
6050 ON S.COrderID = C.COrderID
6051 LEFT OUTER JOIN COrderParty AS O1 WITH(NOLOCK)
6052 ON C.COrderID = O1.COrderID
6053 LEFT OUTER JOIN COrderParty AS O2 WITH(NOLOCK)
6054 ON C.COrderID = O2.COrderID
6055 LEFT OUTER JOIN OrderParty AS PDel WITH(NOLOCK)
6056 ON O1.OrderPartyID = PDel.OrderPartyID AND PDel.[Role] = 'DELIVERYCARRIER'
6057 LEFT OUTER JOIN OrderParty AS PDis WITH(NOLOCK)
6058 ON O2.OrderPartyID = PDis.OrderPartyID AND PDis.[Role] = 'DISPATCHCARRIER'
6059-- LEFT OUTER JOIN Activity AS A WITH(NOLOCK)
6060-- ON R.COServiceID = A.COServiceID
6061-- LEFT OUTER JOIN SPOrder AS SPO WITH(NOLOCK)
6062-- ON A.SPOrderID = SPO.SPOrderID -- AND SPO.Mode = 'LTL' -- 06/18/2008 GANASAD Should show SCAC for all modes, not just LTL.
6063-- LEFT OUTER JOIN SPOParty AS SPOP WITH(NOLOCK)
6064-- ON SPO.SPOrderID = SPOP.SPOrderID
6065-- LEFT OUTER JOIN OrderParty AS SPOP_OP WITH(NOLOCK)
6066-- ON SPOP.OrderPartyID = SPOP_OP.OrderPartyID
6067
6068 -- Consciously ignoring summarizing this because we looked at 10,000
6069 -- records and we have 2 records that have more than one record per
6070 -- record id. Both of them are test records (one of them is NULL and
6071 -- the other is 'test').
6072 DELETE
6073 FROM #SPOrderOther
6074 WHERE
6075 DeliveryCarrierName IS NULL
6076 AND TenderedToCarrierName IS NULL
6077 END
6078
6079 -- =============================================================================================
6080 -- Load #SCAC
6081 -- =============================================================================================
6082
6083 --PRINT 'Load SCAC'
6084
6085 IF @ProcessSCACs = 1
6086 BEGIN
6087 INSERT INTO #SCAC(Scac_RecordID, LTLSCAC)
6088 SELECT DISTINCT
6089 R.RecordID,
6090 (
6091 SELECT DISTINCT
6092 SCAC + ', '
6093 FROM #Row AS R2 WITH(NOLOCK)
6094 INNER JOIN COService AS S2 WITH(NOLOCK)
6095 ON R2.COServiceID = S2.COServiceID
6096 INNER JOIN Activity AS A2 WITH(NOLOCK)
6097 ON S2.COServiceID = A2.COServiceID
6098 INNER JOIN SPOrder AS O2 WITH(NOLOCK)
6099 ON A2.SPOrderID = O2.SPOrderID AND ISNULL(O2.ShipmentType,'H') = 'H'
6100 INNER JOIN SPOParty AS P2 WITH(NOLOCK)
6101 ON O2.SPOrderID = P2.SPOrderID
6102 INNER JOIN OrderParty AS OP2 WITH(NOLOCK)
6103 ON P2.OrderPartyID = OP2.OrderPartyID
6104 WHERE R2.RecordID = R.RecordID AND OP2.SCAC IS NOT NULL
6105 FOR XML PATH('')
6106 ) AS LTLSCAC
6107 FROM #Row AS R
6108 INNER JOIN COService AS S WITH(NOLOCK)
6109 ON R.COServiceID = S.COServiceID
6110 INNER JOIN Activity AS A WITH(NOLOCK)
6111 ON S.COServiceID = A.COServiceID
6112 INNER JOIN SPOrder AS O WITH(NOLOCK)
6113 ON A.SPOrderID = O.SPOrderID AND ISNULL(O.ShipmentType,'H') = 'H'
6114 INNER JOIN SPOParty AS P WITH(NOLOCK)
6115 ON O.SPorderID = P.SPOrderID
6116 INNER JOIN OrderParty AS OP WITH(NOLOCK)
6117 ON P.OrderPartyID = OP.OrderPartyID
6118 END
6119
6120 -- OK02122008===================================================================================
6121 -- Load #Customs
6122 -- =============================================================================================
6123
6124 --PRINT 'Load Customs'
6125
6126 IF @ProcessCustoms = 1
6127 BEGIN
6128 INSERT INTO #Customs
6129 (
6130 Customs_RecordID,
6131 ITNum,
6132 SSLReleaseDate,
6133 EntryLocation,
6134 OGAReleaseDate,
6135 ReceiptDocsDate,
6136 ITLocation,
6137 EntryDate,
6138 ExamRequiredDate,
6139 TenderedToCarrierDate,
6140 FDAEntry,
6141 ITDate,
6142 EntryNum,
6143 CustomsHoldDate,
6144 TurnedOverDate,
6145 FDAReqDate,
6146 ReleaseDate,
6147 BrokerName,
6148 OGAHoldDate,
6149 Notes,
6150 FDASubmitDate,
6151 ISFID,
6152 ISFDate,
6153 DeclaredValue
6154 )
6155
6156 SELECT
6157 R.RecordID AS Customs_RecordID,
6158 ISNULL(C.ITNumber,'') AS ITNumber,
6159 C.SSLReleaseDate AS SSLReleaseDate,
6160 ISNULL(C.EntryLocation,'') AS EntryLocation,
6161 C.OGAReleaseDate AS OGAReleaseDate,
6162 ISNULL(C.ReceiptDocsDateText,'')AS ReceiptDocsDate,
6163 ISNULL(C.ITLocation,'') AS ITLocation,
6164 C.EntryDate AS EntryDate,
6165 C.ExamRequiredDate AS ExamRequiredDate,
6166 C.DispatchedDate AS TenderedToCarrierDate,
6167 ISNULL(C.FDAEntryDateText,'') AS FDAEntryDate,
6168 C.ITDate AS ITDate,
6169 ISNULL(C.EntryNumber,'') AS EntryNum,
6170 C.CustomsHoldDate AS CustomsHoldDate,
6171 C.TurnedOverDate AS TurnedOverDate,
6172 ISNULL(C.FDARequestDateText,'') AS FDAReqDate,
6173 C.ReleaseDate AS ReleaseDate,
6174 ISNULL(C.BrokerName,'') AS BrokerName,
6175 C.OGAHoldDate AS OGAHoldDate,
6176 ISNULL(C.Notes,'') AS Notes,
6177 ISNULL(C.FDASubmitDateText,'') AS FDASubmitDate,
6178 ISNULL(C.ISFID, '') AS ISFID,
6179 ISNULL(CONVERT(VARCHAR, C.ISFDate, 101), ''),
6180 NULLIF(C.DeclaredValue, 0) AS DeclaredValue
6181 FROM [#Row] AS R
6182 INNER JOIN Customs AS C WITH(NOLOCK)
6183 ON R.CustomsCOServiceID = C.COServiceID
6184 UNION
6185
6186 SELECT
6187 R.RecordID AS Customs_RecordID,
6188 ISNULL(C.ITNumber,'') AS ITNumber,
6189 C.SSLReleaseDate AS SSLReleaseDate,
6190 ISNULL(C.EntryLocation,'') AS EntryLocation,
6191 C.OGAReleaseDate AS OGAReleaseDate,
6192 ISNULL(C.ReceiptDocsDateText,'')AS ReceiptDocsDate,
6193 ISNULL(C.ITLocation,'') AS ITLocation,
6194 C.EntryDate AS EntryDate,
6195 C.ExamRequiredDate AS ExamRequiredDate,
6196 C.DispatchedDate AS TenderedToCarrierDate,
6197 ISNULL(C.FDAEntryDateText,'') AS FDAEntryDate,
6198 C.ITDate AS ITDate,
6199 ISNULL(C.EntryNumber,'') AS EntryNum,
6200 C.CustomsHoldDate AS CustomsHoldDate,
6201 C.TurnedOverDate AS TurnedOverDate,
6202 ISNULL(C.FDARequestDateText,'') AS FDAReqDate,
6203 C.ReleaseDate AS ReleaseDate,
6204 ISNULL(C.BrokerName,'') AS BrokerName,
6205 C.OGAHoldDate AS OGAHoldDate,
6206 ISNULL(C.Notes,'') AS Notes,
6207 ISNULL(C.FDASubmitDateText,'') AS FDASubmitDate,
6208 ISNULL(C.ISFID, '') AS ISFID,
6209 ISNULL(CONVERT(VARCHAR, C.ISFDate, 101), ''),
6210 NULLIF(C.DeclaredValue, 0) AS DeclaredValue
6211 FROM [#Row] AS R
6212 INNER JOIN Customs AS C WITH(NOLOCK)
6213 ON R.COServiceID = C.COServiceID
6214
6215 UPDATE C
6216 SET DeleteFlg = 1
6217 FROM #Customs AS C
6218 WHERE EXISTS (SELECT 1 FROM #Customs AS C2
6219 WHERE C.Customs_RecordID = C2.Customs_RecordID
6220 GROUP BY C2.Customs_RecordID
6221 HAVING COUNT(1) > 1
6222 )
6223
6224 INSERT INTO #Customs
6225 (
6226 Customs_RecordID,
6227 ITNum,
6228 SSLReleaseDate,
6229 EntryLocation,
6230 OGAReleaseDate,
6231 ReceiptDocsDate,
6232 ITLocation,
6233 EntryDate,
6234 ExamRequiredDate,
6235 TenderedToCarrierDate,
6236 FDAEntry,
6237 ITDate,
6238 EntryNum,
6239 CustomsHoldDate,
6240 TurnedOverDate,
6241 FDAReqDate,
6242 ReleaseDate,
6243 BrokerName,
6244 OGAHoldDate,
6245 Notes,
6246 FDASubmitDate,
6247 ISFID,
6248 ISFDate,
6249 DeclaredValue
6250 )
6251 SELECT DISTINCT
6252 C.Customs_RecordID,
6253 SUBSTRING((
6254 SELECT C2.ITNum + ', '
6255 FROM #Customs AS C2
6256 WHERE C.Customs_RecordID = C2.Customs_RecordID
6257 GROUP BY ITNum
6258 FOR XML PATH('')
6259 ),1,500) AS ITNum,
6260 MIN(C.SSLReleaseDate) AS SSLReleaseDate,
6261 SUBSTRING((
6262 SELECT C2.EntryLocation + ', '
6263 FROM #Customs AS C2
6264 WHERE C.Customs_RecordID = C2.Customs_RecordID
6265 GROUP BY EntryLocation
6266 FOR XML PATH('')
6267 ),1,650) AS EntryLocation,
6268 MIN(C.OGAReleaseDate) AS OGAReleaseDate,
6269 SUBSTRING((
6270 SELECT C2.ReceiptDocsDate + ', '
6271 FROM #Customs AS C2
6272 WHERE C.Customs_RecordID = C2.Customs_RecordID
6273 GROUP BY ReceiptDocsDate
6274 FOR XML PATH('')
6275 ),1,500) AS ReceiptDocsDate,
6276 SUBSTRING((
6277 SELECT C2.ITLocation + ', '
6278 FROM #Customs AS C2
6279 WHERE C.Customs_RecordID = C2.Customs_RecordID
6280 GROUP BY ITLocation
6281 FOR XML PATH('')
6282 ),1,650) AS ITLocation,
6283 MIN(EntryDate) AS EntryDate,
6284 MIN(ExamRequiredDate) AS ExamRequiredDate,
6285 MIN(TenderedToCarrierDate) AS TenderedToCarrierDate,
6286 SUBSTRING((
6287 SELECT C2.FDAEntry + ', '
6288 FROM #Customs AS C2
6289 WHERE C.Customs_RecordID = C2.Customs_RecordID
6290 GROUP BY FDAEntry
6291 FOR XML PATH('')
6292 ),1,500) AS FDAEntry,
6293 MIN(C.ITDate) AS ITDate,
6294 SUBSTRING((
6295 SELECT C2.EntryNum + ', '
6296 FROM #Customs AS C2
6297 WHERE C.Customs_RecordID = C2.Customs_RecordID
6298 GROUP BY EntryNum
6299 FOR XML PATH('')
6300 ),1,200) AS EntryNum,
6301 MIN(C.CustomsHoldDate) AS CustomsHoldDate,
6302 MIN(C.TurnedOverDate) AS TurnedOverDate,
6303 SUBSTRING((
6304 SELECT C2.FDAReqDate + ', '
6305 FROM #Customs AS C2
6306 WHERE C.Customs_RecordID = C2.Customs_RecordID
6307 GROUP BY FDAReqDate
6308 FOR XML PATH('')
6309 ),1,500) AS FDAReqDate,
6310 MIN(C.ReleaseDate) AS ReleaseDate,
6311 SUBSTRING((
6312 SELECT C2.BrokerName + ', '
6313 FROM #Customs AS C2
6314 WHERE C.Customs_RecordID = C2.Customs_RecordID
6315 GROUP BY BrokerName
6316 FOR XML PATH('')
6317 ),1,250) AS BrokerName,
6318 MIN(C.OGAHoldDate) AS OGAHoldDate,
6319 SUBSTRING((
6320 SELECT C2.Notes + ', '
6321 FROM #Customs AS C2
6322 WHERE C.Customs_RecordID = C2.Customs_RecordID
6323 GROUP BY Notes
6324 FOR XML PATH('')
6325 ),1,2550) AS Notes,
6326 SUBSTRING((
6327 SELECT C2.FDASubmitDate + ', '
6328 FROM #Customs AS C2
6329 WHERE C.Customs_RecordID = C2.Customs_RecordID
6330 GROUP BY FDASubmitDate
6331 FOR XML PATH('')
6332 ),1,2550) AS FDASubmitDate,
6333 SUBSTRING((
6334 SELECT C2.ISFID + ', '
6335 FROM #Customs AS C2
6336 WHERE C.Customs_RecordID = C2.Customs_RecordID AND C2.ISFID != ''
6337 GROUP BY ISFID
6338 FOR XML PATH('')
6339 ),1,2550) AS ISFID,
6340 SUBSTRING((
6341 SELECT C2.ISFDate + ', '
6342 FROM #Customs AS C2
6343 WHERE C.Customs_RecordID = C2.Customs_RecordID AND C2.ISFDate != ''
6344 GROUP BY ISFDate
6345 FOR XML PATH('')
6346 ),1,2550) AS ISFDate,
6347 SUM(C.DeclaredValue) AS DeclaredValue
6348 FROM #Customs AS C
6349 WHERE DeleteFlg = 1
6350 GROUP BY Customs_RecordID
6351
6352 DELETE FROM #Customs WHERE DeleteFlg = 1
6353
6354 END
6355
6356 -- FAB02122008==================================================================================
6357 -- Load #PoolCrossLocation
6358 -- =============================================================================================
6359
6360 --PRINT 'Load PoolCrossLocation'
6361
6362 IF @ProcessPoolCrossLocations = 1
6363 BEGIN
6364
6365 ;WITH PPCDTypes(PPCDType) AS
6366 (
6367 SELECT 'PP' UNION ALL
6368SELECT 'PD' UNION ALL
6369 SELECT 'XP' UNION ALL
6370 SELECT 'XD'
6371 )
6372
6373 INSERT INTO #PoolCrossLocation
6374 (
6375 PoolCrossLocation_RecordID,
6376 PoolpointName,
6377 PoolpointCity,
6378 PoolpointState,
6379 CrossDockName,
6380 CrossDockCity,
6381 CrossDockState
6382 )
6383
6384 SELECT DISTINCT
6385 R.RecordID,
6386 CASE T.PPCDType
6387 WHEN 'PP' THEN DL.[Name]
6388 WHEN 'PD' THEN DL.[Name]
6389 ELSE NULL
6390 END,
6391 CASE T.PPCDType
6392 WHEN 'PP' THEN DL.City
6393 WHEN 'PD' THEN DL.City
6394 ELSE NULL
6395 END,
6396 CASE T.PPCDType
6397 WHEN 'PP' THEN DL.State
6398 WHEN 'PD' THEN DL.State
6399 ELSE NULL
6400 END,
6401 CASE T.PPCDType
6402 WHEN 'XP' THEN DL.[Name]
6403 WHEN 'XD' THEN DL.[Name]
6404 ELSE NULL
6405 END,
6406 CASE T.PPCDType
6407 WHEN 'XP' THEN DL.City
6408 WHEN 'XD' THEN DL.City
6409 ELSE NULL
6410 END,
6411 CASE T.PPCDType
6412 WHEN 'XP' THEN DL.State
6413 WHEN 'XD' THEN DL.State
6414 ELSE NULL
6415 END
6416
6417 FROM #Row AS R
6418 INNER JOIN COLocation AS L WITH(NOLOCK)
6419 ON R.COSDetailID = L.COSDetailID
6420 INNER JOIN PPCDTypes AS T WITH(NOLOCK)
6421 ON L.COLocationType = T.PPCDType
6422 INNER JOIN NTSR.dbo.DimLocation AS DL WITH(NOLOCK)
6423 ON L.KeyLocationID = DL.KeyLocationID
6424 END
6425
6426 -- OK02132008===================================================================================
6427 -- Load #PoolCrossLocationDate
6428 -- =============================================================================================
6429
6430 --PRINT 'Load PoolCrossLocationDate'
6431
6432 -- Note: Should already be summarized because we're summarizing the subselects by RecordID
6433 -- and the DateType.
6434 IF @ProcessPoolCrossLocationDates = 1
6435 BEGIN
6436 ;WITH WantedDateTypes(DateTimeType) AS
6437 (
6438 SELECT 'Poolpoint Scheduled Arrival Time' UNION ALL
6439 SELECT 'Poolpoint Scheduled Departure Time' UNION ALL
6440 SELECT 'Poolpoint Actual Arrival Time' UNION ALL
6441 SELECT 'Poolpoint Actual Departure Time' UNION ALL
6442 SELECT 'Cross Dock Actual Arrival Time' UNION ALL
6443 SELECT 'Cross Dock Scheduled Departure Time' UNION ALL
6444 SELECT 'Cross Dock Actual Departure Time' UNION ALL
6445
6446 SELECT 'Poolpoint Scheduled Arrival Date' UNION ALL
6447 SELECT 'Poolpoint Scheduled Departure Date' UNION ALL
6448 SELECT 'Poolpoint Actual Arrival Date' UNION ALL
6449 SELECT 'Poolpoint Actual Departure Date' UNION ALL
6450 SELECT 'Cross Dock Actual Arrival Date' UNION ALL
6451 SELECT 'Cross Dock Scheduled Departure Date' UNION ALL
6452 SELECT 'Cross Dock Actual Departure Date'
6453 )
6454
6455 INSERT INTO [#PoolCrossLocationDate]
6456 (
6457 PoolCrossLocationDate_RecordID,
6458 PoolpointSchedArrivalDate,
6459 PoolpointSchedArrivalTime,
6460 PoolpointSchedDepartDate,
6461 PoolpointSchedDepartTime,
6462 PoolpointActualArrivalDate,
6463 PoolpointActualArrivalTime,
6464 PoolpointActualDepartDate,
6465 PoolpointActualDepartTime,
6466 CrossDockArrivalDate,
6467 CrossDockArrivalTime,
6468 CrossDockSchedDepartDate,
6469 CrossDockSchedDepartTime,
6470 CrossDockActualDepartDate,
6471 CrossDockActualDepartTime
6472 )
6473
6474 SELECT
6475 RecordID,
6476 [Poolpoint Scheduled Arrival Date],
6477 [Poolpoint Scheduled Arrival Time],
6478 [Poolpoint Scheduled Departure Date],
6479 [Poolpoint Scheduled Departure Time],
6480 [Poolpoint Actual Arrival Date],
6481 [Poolpoint Actual Arrival Time],
6482 [Poolpoint Actual Departure Date],
6483 [Poolpoint Actual Departure Time],
6484 [Cross Dock Actual Arrival Date],
6485 [Cross Dock Actual Arrival Time],
6486 [Cross Dock Scheduled Departure Date],
6487 [Cross Dock Scheduled Departure Time],
6488[Cross Dock Actual Departure Date],
6489 [Cross Dock Actual Departure Time]
6490 FROM
6491 (
6492 SELECT R.RecordID, LD.DateTimeType, MIN(LD.DateTimeValue) AS DateTimeValue
6493 FROM #Row AS R
6494 INNER JOIN COLocation AS L WITH(NOLOCK)
6495 ON R.COSDetailID = L.COSDetailID
6496 INNER JOIN [#UnpivotedCOLocationDates] AS LD
6497 ON L.COLocationID = LD.COLocationID
6498 INNER JOIN WantedDateTypes AS WDT WITH(NOLOCK)
6499 ON LD.DateTimeType = WDT.DateTimeType
6500 GROUP BY R.RecordID, LD.DateTimeType
6501 ) AS UP
6502
6503 PIVOT
6504 (
6505 MAX(up.DateTimeValue) FOR up.DateTimeType IN
6506 (
6507 [Poolpoint Scheduled Arrival Date],
6508 [Poolpoint Scheduled Arrival Time],
6509 [Poolpoint Scheduled Departure Date],
6510 [Poolpoint Scheduled Departure Time],
6511 [Cross Dock Scheduled Departure Date],
6512 [Cross Dock Scheduled Departure Time],
6513 [Poolpoint Actual Arrival Date],
6514 [Poolpoint Actual Arrival Time],
6515 [Poolpoint Actual Departure Date],
6516 [Poolpoint Actual Departure Time],
6517 [Cross Dock Actual Arrival Date],
6518 [Cross Dock Actual Arrival Time],
6519 [Cross Dock Actual Departure Date],
6520 [Cross Dock Actual Departure Time]
6521 )
6522 ) AS p
6523 END
6524
6525 IF @ProcessLoad = 1 BEGIN
6526 INSERT INTO #Load (
6527 Load_RecordID,
6528 LoadNumber,
6529 LoadHotY,
6530 CustomEquipmentTypeID,
6531 CustomEquipmentType
6532 )
6533 SELECT
6534 R.RecordID,
6535 R.LoadNumber,
6536 CASE
6537 WHEN L.RatingRDN = 2228 THEN 1
6538 ELSE NULL
6539 END AS LoadHotY,
6540 L.CustomEquipmentTypeID,
6541 NULL
6542 FROM #Row R
6543 INNER JOIN dbo.[Load] L
6544 ON R.LoadNumber = L.LoadNumber
6545 WHERE
6546 1 = 1
6547 --if you add another column to this table, u probably want to remove the below line,
6548 --otherwise this will only insert loads that are hot! (we should consider indexing if removed)
6549 -- L.RatingRDN = 2228
6550
6551 IF EXISTS(SELECT TOP 1 CustomEquipmentTypeID FROM #Load WHERE ISNULL(CustomEquipmentTypeID,0) > 0) BEGIN
6552 UPDATE L
6553 SET L.CustomEquipmentType = CET.EquipmentName
6554 FROM #Load L
6555 INNER JOIN [MDMPublicReadOnly].[mdm].[CustomEquipmentType] AS CET WITH (NOLOCK)
6556 ON L.CustomEquipmentTypeID = CET.CustomEquipmentTypeID
6557 END
6558 END
6559
6560
6561 -- OK02142008=======================================================================
6562 -- Load #Refs
6563 -- =================================================================================
6564
6565 --PRINT 'Loading Refs'
6566
6567 CREATE TABLE #RefType
6568 (
6569 ReferenceType VARCHAR(50)
6570 )
6571
6572 INSERT INTO #RefType (ReferenceType)
6573 SELECT 'PO' UNION ALL
6574 SELECT 'PU' UNION ALL
6575 SELECT 'SBOL' UNION ALL
6576 SELECT 'ShipID' UNION ALL
6577 SELECT 'SHID' UNION ALL
6578 SELECT 'Ship ID' UNION ALL
6579 SELECT 'CustPO' UNION ALL
6580 SELECT 'DistPO' UNION ALL
6581 SELECT 'DEL' UNION ALL
6582 SELECT 'GL' UNION ALL
6583 SELECT 'VPO' UNION ALL
6584 SELECT 'JNO' UNION ALL
6585 SELECT 'CCTR' UNION ALL
6586 SELECT 'CIN' UNION ALL
6587 SELECT 'CommercialInvoiceNum'
6588
6589 CREATE TABLE #WantedRefTypes
6590 (
6591 RefTypeInDestTable VARCHAR(50),
6592 RefTypeInSourceTable VARCHAR(50),
6593 RefSubTypeInSourceTable VARCHAR(50)
6594 )
6595
6596
6597 --PRINT 'Exists CustRefNum?'
6598
6599 IF EXISTS(SELECT 1 FROM #Column AS C WHERE C.CName = 'CustRefNum')
6600 BEGIN
6601 INSERT INTO [#WantedRefTypes] (RefTypeInDestTable,RefTypeInSourceTable,RefSubTypeInSourceTable)
6602 SELECT 'CustRefNum', 'RefNum', 'Customer'
6603
6604 INSERT INTO [#WantedRefTypes] (RefTypeInDestTable,RefTypeInSourceTable,RefSubTypeInSourceTable)
6605 SELECT 'CustRefNum', 'CommercialInvoiceNumber', 'Customer'
6606
6607 INSERT INTO #Ref(ReferenceType)
6608 VALUES ('CustRefNum')
6609 END
6610
6611 --PRINT 'Exists MasterPO?'
6612
6613 IF EXISTS(SELECT 1 FROM #Column AS C WHERE C.CName = 'MasterPO')
6614 BEGIN
6615 INSERT INTO [#WantedRefTypes] (RefTypeInDestTable,RefTypeInSourceTable,RefSubTypeInSourceTable)
6616 SELECT 'MasterPO', 'MasterPO', ''
6617
6618 INSERT INTO [#WantedRefTypes] (RefTypeInDestTable,RefTypeInSourceTable,RefSubTypeInSourceTable)
6619 SELECT 'MasterPO', 'MasterPO', 'Payer'
6620
6621 INSERT INTO #Ref(ReferenceType)
6622 VALUES ('MasterPO')
6623 END
6624
6625 --PRINT 'Exists PayerRefNum?'
6626
6627 IF EXISTS(SELECT 1 FROM #Column AS C WHERE C.CName = 'PayerRefNum')
6628 BEGIN
6629 INSERT INTO [#WantedRefTypes] (RefTypeInDestTable,RefTypeInSourceTable,RefSubTypeInSourceTable)
6630 SELECT 'PayerRefNum', 'RefNum', 'Payer'
6631
6632 INSERT INTO #Ref(ReferenceType)
6633 VALUES ('PayerRefNum')
6634 END
6635
6636 --PRINT 'Exists CarrierProNum?'
6637
6638 IF EXISTS(SELECT 1 FROM #Column AS C WHERE C.CName = 'CarrierProNum')
6639 BEGIN
6640 INSERT INTO [#WantedRefTypes] (RefTypeInDestTable,RefTypeInSourceTable,RefSubTypeInSourceTable)
6641 SELECT 'CarrierProNum', 'PRONUMBER', ''
6642
6643 -- If somebody ever reads this, we'll buy you lunch. Scott Schottler
6644 INSERT INTO #Ref(ReferenceType)
6645 VALUES ('CarrierProNum')
6646 END
6647
6648 --PRINT 'Exists ShipperReference?'
6649
6650 IF EXISTS(SELECT 1 FROM #Column AS C WHERE C.CName = 'ShipperReference')
6651 BEGIN
6652 INSERT INTO [#WantedRefTypes] (RefTypeInDestTable,RefTypeInSourceTable,RefSubTypeInSourceTable)
6653 SELECT 'ShipperReference', 'RefNum', 'Shipper'
6654
6655 INSERT INTO #Ref(ReferenceType)
6656 VALUES ('ShipperReference')
6657 END
6658
6659 --PRINT 'Exists OrderNum?'
6660
6661 IF EXISTS(SELECT 1 FROM #Column AS C WHERE C.CName = 'OrderNum')
6662BEGIN
6663 INSERT INTO [#WantedRefTypes] (RefTypeInDestTable,RefTypeInSourceTable,RefSubTypeInSourceTable)
6664 SELECT 'OrderNum', 'OrderNum', 'Express'
6665
6666 INSERT INTO #Ref(ReferenceType)
6667 VALUES ('OrderNum')
6668 END
6669
6670 --PRINT 'Exists CustLoadNum?'
6671
6672 IF EXISTS(SELECT 1 FROM #Column AS C WHERE C.CName = 'CustLoadNum')
6673 BEGIN
6674 INSERT INTO [#WantedRefTypes] (RefTypeInDestTable,RefTypeInSourceTable,RefSubTypeInSourceTable)
6675 SELECT 'CustLoadNum', 'CustLoadNumber', 'Customer'
6676
6677 INSERT INTO #Ref(ReferenceType)
6678 VALUES ('CustLoadNum')
6679 END
6680
6681 --PRINT 'Exists MBOL?'
6682
6683 IF EXISTS(SELECT 1 FROM #Column AS C WHERE C.CName = 'MBOL')
6684 BEGIN
6685 INSERT INTO [#WantedRefTypes] (RefTypeInDestTable,RefTypeInSourceTable,RefSubTypeInSourceTable)
6686 SELECT 'MBOL', 'MBOL', '' --04/03/2008 Steve Change Subtype to '' instead of 'Customer'
6687
6688 INSERT INTO #Ref(ReferenceType)
6689 VALUES ('MBOL')
6690 END
6691
6692 --PRINT 'Exists MasterAWB?'
6693
6694 IF EXISTS(SELECT 1 FROM #Column AS C WHERE C.CName = 'MasterAWB')
6695 BEGIN
6696 INSERT INTO [#WantedRefTypes] (RefTypeInDestTable,RefTypeInSourceTable,RefSubTypeInSourceTable)
6697 SELECT 'MasterAWB', 'MAWB', '' --04/03/2008 Steve Change Subtype to '' instead of 'Customer'
6698
6699 INSERT INTO #Ref(ReferenceType)
6700 VALUES ('MasterAWB')
6701 END
6702
6703 --PRINT 'Exists AirlineWayBill?'
6704 IF EXISTS(SELECT 1 FROM #Column AS C WHERE C.CName = 'AirlineWayBill')
6705 BEGIN
6706 INSERT INTO [#WantedRefTypes] (RefTypeInDestTable,RefTypeInSourceTable,RefSubTypeInSourceTable)
6707SELECT 'AirlineWayBill', 'PRONUMBER', ''
6708
6709 INSERT INTO #Ref(ReferenceType)
6710 VALUES ('AirlineWayBill')
6711 END
6712
6713
6714 --PRINT 'Exists HBOL?'
6715
6716 IF EXISTS(SELECT 1 FROM #Column AS C WHERE C.CName IN ('HBOL','AirlineWayBill'))
6717 BEGIN
6718 INSERT INTO [#WantedRefTypes] (RefTypeInDestTable,RefTypeInSourceTable,RefSubTypeInSourceTable)
6719 SELECT 'HBOL', 'HBOL', ''
6720
6721 INSERT INTO #Ref(ReferenceType)
6722 VALUES ('HBOL')
6723 END
6724
6725 --PRINT 'Exists SSLineBOL?'
6726
6727 IF EXISTS(SELECT 1 FROM #Column AS C WHERE C.CName = 'SSLineBOL')
6728 BEGIN
6729 INSERT INTO [#WantedRefTypes] (RefTypeInDestTable,RefTypeInSourceTable,RefSubTypeInSourceTable)
6730 SELECT 'SSLineBOL', 'SSLineBOL', ''
6731
6732 INSERT INTO #Ref(ReferenceType)
6733 VALUES ('SSLineBOL')
6734 END
6735
6736 --PRINT 'Exists PickupNum?'
6737
6738 IF EXISTS(SELECT 1 FROM #Column AS C WHERE C.CName = 'PickupNum')
6739 BEGIN
6740 INSERT INTO [#WantedRefTypes] (RefTypeInDestTable,RefTypeInSourceTable,RefSubTypeInSourceTable)
6741 SELECT 'PickupNum', 'RefNum', 'Origin'
6742
6743 INSERT INTO #Ref(ReferenceType)
6744 VALUES ('PickupNum')
6745 END
6746
6747 --PRINT 'Exists DeliveryNum?'
6748
6749 IF EXISTS(SELECT 1 FROM #Column AS C WHERE C.CName = 'DeliveryNum')
6750 BEGIN
6751 INSERT INTO [#WantedRefTypes] (RefTypeInDestTable,RefTypeInSourceTable,RefSubTypeInSourceTable)
6752 SELECT 'DeliveryNum', 'RefNum', 'Destination'
6753
6754 INSERT INTO #Ref(ReferenceType)
6755 VALUES ('DeliveryNum')
6756 END
6757
6758 --PRINT 'Exists BOL?'
6759
6760 IF EXISTS(SELECT 1 FROM #Column AS C WHERE C.CName = 'BOL')
6761 BEGIN
6762 INSERT INTO [#WantedRefTypes] (RefTypeInDestTable,RefTypeInSourceTable,RefSubTypeInSourceTable)
6763 SELECT 'BOL', 'BOL', ''
6764
6765 INSERT INTO #Ref(ReferenceType)
6766 VALUES ('BOL')
6767 END
6768
6769 --PRINT 'Exists SubHBOL?'
6770
6771 IF EXISTS(SELECT 1 FROM #Column AS C WHERE C.CName = 'SubHBOL')
6772 BEGIN
6773 INSERT INTO [#WantedRefTypes] (RefTypeInDestTable,RefTypeInSourceTable,RefSubTypeInSourceTable)
6774 SELECT 'SubHBOL', 'SBOL', ''
6775
6776 INSERT INTO #Ref(ReferenceType)
6777 VALUES ('SubHBOL')
6778 END
6779
6780 --PRINT 'Exists ConfirmationNumber?'
6781
6782 -- Confirmation Number
6783 IF EXISTS(SELECT 1 FROM #Column AS C WHERE C.CName = 'ConfirmationNumber')
6784 BEGIN
6785 INSERT INTO [#Ref] (Ref_RecordID,ReferenceType,ReferenceSubType,ReferenceNumber)
6786 SELECT
6787 R.RecordID,
6788 'ConfirmationNumber',
6789 '',
6790 N.CHRNumber
6791 FROM #Row AS R
6792 INNER JOIN COSNumber AS N WITH(NOLOCK)
6793 ON R.COServiceID = N.COServiceID AND N.CHRNumberType='CFRM'
6794
6795 INSERT INTO #Ref(ReferenceType)
6796 VALUES ('ConfirmationNumber')
6797 END
6798
6799 IF EXISTS(SELECT 1 FROM #Column AS C WHERE C.CName = 'ActArriDt')
6800 BEGIN
6801 INSERT INTO [#WantedRefTypes] (RefTypeInDestTable,RefTypeInSourceTable,RefSubTypeInSourceTable)
6802 SELECT 'ActArriDt', 'ActArriDt', 'SubOrder'
6803
6804 INSERT INTO #Ref(ReferenceType)
6805 VALUES ('ActArriDt')
6806 END
6807
6808 IF EXISTS(SELECT 1 FROM #Column AS C WHERE C.CName = 'ActDepDt')
6809 BEGIN
6810 INSERT INTO [#WantedRefTypes] (RefTypeInDestTable,RefTypeInSourceTable,RefSubTypeInSourceTable)
6811 SELECT 'ActDepDt', 'ActDepDt', 'SubOrder'
6812
6813 INSERT INTO #Ref(ReferenceType)
6814 VALUES ('ActDepDt')
6815 END
6816
6817 IF EXISTS(SELECT 1 FROM #Column AS C WHERE C.CName = 'BOLREF')
6818 BEGIN
6819
6820 UpDate #Column
6821 SET CName = 'BOL'
6822 Where CName = 'BOL'
6823
6824 SET @SelectClause = REPLACE(@SelectClause, 'BOLREF', 'BOL')
6825
6826 INSERT INTO [#WantedRefTypes] (RefTypeInDestTable,RefTypeInSourceTable,RefSubTypeInSourceTable)
6827 SELECT 'BOL', 'BOL', 'SubOrder'
6828
6829 INSERT INTO #Ref(ReferenceType)
6830 VALUES ('BOL')
6831 END
6832
6833 IF EXISTS(SELECT 1 FROM #Column AS C WHERE C.CName = 'CCTR')
6834 BEGIN
6835 INSERT INTO [#WantedRefTypes] (RefTypeInDestTable,RefTypeInSourceTable,RefSubTypeInSourceTable)
6836 SELECT 'CCTR', 'CCTR', 'Destination'
6837
6838 INSERT INTO #Ref(ReferenceType)
6839 VALUES ('CCTR')
6840 END
6841
6842 IF EXISTS(SELECT 1 FROM #Column AS C WHERE C.CName = 'CITTN')
6843 BEGIN
6844 INSERT INTO [#WantedRefTypes] (RefTypeInDestTable,RefTypeInSourceTable,RefSubTypeInSourceTable)
6845 SELECT 'CITTN', 'CITTN', 'SubOrder'
6846
6847 INSERT INTO #Ref(ReferenceType)
6848 VALUES ('CITTN')
6849 END
6850
6851IF EXISTS(SELECT 1 FROM #Column AS C WHERE C.CName = 'CON')
6852 BEGIN
6853 INSERT INTO [#WantedRefTypes] (RefTypeInDestTable,RefTypeInSourceTable,RefSubTypeInSourceTable)
6854 SELECT 'CON', 'CON', 'SubOrder'
6855
6856 INSERT INTO #Ref(ReferenceType)
6857 VALUES ('CON')
6858 END
6859
6860IF EXISTS(SELECT 1 FROM #Column AS C WHERE C.CName = 'CRID')
6861 BEGIN
6862 INSERT INTO [#WantedRefTypes] (RefTypeInDestTable,RefTypeInSourceTable,RefSubTypeInSourceTable)
6863 SELECT 'CRID', 'CRID', 'SubOrder'
6864
6865 INSERT INTO #Ref(ReferenceType)
6866 VALUES ('CRID')
6867 END
6868
6869IF EXISTS(SELECT 1 FROM #Column AS C WHERE C.CName = 'DEL')
6870 BEGIN
6871 INSERT INTO [#WantedRefTypes] (RefTypeInDestTable,RefTypeInSourceTable,RefSubTypeInSourceTable)
6872 SELECT 'DEL', 'DEL', 'Destination'
6873
6874 INSERT INTO #Ref(ReferenceType)
6875 VALUES ('DEL')
6876 END
6877
6878IF EXISTS(SELECT 1 FROM #Column AS C WHERE C.CName = 'DIST')
6879 BEGIN
6880 INSERT INTO [#WantedRefTypes] (RefTypeInDestTable,RefTypeInSourceTable,RefSubTypeInSourceTable)
6881 SELECT 'DIST', 'DIST', 'SubOrder'
6882
6883 INSERT INTO #Ref(ReferenceType)
6884 VALUES ('DIST')
6885
6886 END
6887
6888IF EXISTS(SELECT 1 FROM #Column AS C WHERE C.CName = 'DIV')
6889 BEGIN
6890 INSERT INTO [#WantedRefTypes] (RefTypeInDestTable,RefTypeInSourceTable,RefSubTypeInSourceTable)
6891 SELECT 'DIV', 'DIV', 'SubOrder'
6892
6893 INSERT INTO #Ref(ReferenceType)
6894 VALUES ('DIV')
6895
6896 END
6897
6898IF EXISTS(SELECT 1 FROM #Column AS C WHERE C.CName = 'FDA')
6899 BEGIN
6900 INSERT INTO [#WantedRefTypes] (RefTypeInDestTable,RefTypeInSourceTable,RefSubTypeInSourceTable)
6901 SELECT 'FDA', 'FDA', 'SubOrder'
6902
6903 INSERT INTO #Ref(ReferenceType)
6904 VALUES ('FDA')
6905
6906 END
6907
6908IF EXISTS(SELECT 1 FROM #Column AS C WHERE C.CName = 'GL')
6909 BEGIN
6910 INSERT INTO [#WantedRefTypes] (RefTypeInDestTable,RefTypeInSourceTable,RefSubTypeInSourceTable)
6911 SELECT 'GL', 'GL', 'SubOrder'
6912
6913 INSERT INTO #Ref(ReferenceType)
6914 VALUES ('GL')
6915
6916 END
6917
6918IF EXISTS(SELECT 1 FROM #Column AS C WHERE C.CName = 'JNO')
6919 BEGIN
6920 INSERT INTO [#WantedRefTypes] (RefTypeInDestTable,RefTypeInSourceTable,RefSubTypeInSourceTable)
6921 SELECT 'JNO', 'JNO', 'SubOrder'
6922
6923 INSERT INTO #Ref(ReferenceType)
6924 VALUES ('JNO')
6925
6926 END
6927
6928IF EXISTS(SELECT 1 FROM #Column AS C WHERE C.CName = 'LIC')
6929 BEGIN
6930 INSERT INTO [#WantedRefTypes] (RefTypeInDestTable,RefTypeInSourceTable,RefSubTypeInSourceTable)
6931 SELECT 'LIC', 'LIC', 'SubOrder'
6932
6933 INSERT INTO #Ref(ReferenceType)
6934 VALUES ('LIC')
6935
6936 END
6937
6938IF EXISTS(SELECT 1 FROM #Column AS C WHERE C.CName = 'LOAD')
6939 BEGIN
6940 INSERT INTO [#WantedRefTypes] (RefTypeInDestTable,RefTypeInSourceTable,RefSubTypeInSourceTable)
6941 SELECT 'LOAD', 'LOAD', 'SubOrder'
6942
6943 INSERT INTO #Ref(ReferenceType)
6944 VALUES ('LOAD')
6945
6946 END
6947
6948IF EXISTS(SELECT 1 FROM #Column AS C WHERE C.CName = 'MBOLREF')
6949 BEGIN
6950
6951 UpDate #Column
6952 SET CName = 'MBOL'
6953 Where CName = 'MBOLREF'
6954
6955 SET @SelectClause = REPLACE(@SelectClause, 'MBOLREF', 'MBOL')
6956
6957 INSERT INTO [#WantedRefTypes] (RefTypeInDestTable,RefTypeInSourceTable,RefSubTypeInSourceTable)
6958 SELECT 'MBOL', 'MBOL', 'SubOrder'
6959
6960 INSERT INTO #Ref(ReferenceType)
6961 VALUES ('MBOL')
6962
6963 END
6964
6965IF EXISTS(SELECT 1 FROM #Column AS C WHERE C.CName = 'MREF')
6966 BEGIN
6967 INSERT INTO [#WantedRefTypes] (RefTypeInDestTable,RefTypeInSourceTable,RefSubTypeInSourceTable)
6968 SELECT 'MREF', 'MREF', 'SubOrder'
6969
6970 INSERT INTO #Ref(ReferenceType)
6971 VALUES ('MREF')
6972
6973 END
6974
6975IF EXISTS(SELECT 1 FROM #Column AS C WHERE C.CName = 'ORD')
6976 BEGIN
6977 INSERT INTO [#WantedRefTypes] (RefTypeInDestTable,RefTypeInSourceTable,RefSubTypeInSourceTable)
6978 SELECT 'ORD', 'ORD', 'SubOrder'
6979
6980 INSERT INTO #Ref(ReferenceType)
6981 VALUES ('ORD')
6982
6983 END
6984
6985IF EXISTS(SELECT 1 FROM #Column AS C WHERE C.CName = 'OrderID')
6986 BEGIN
6987 INSERT INTO [#WantedRefTypes] (RefTypeInDestTable,RefTypeInSourceTable,RefSubTypeInSourceTable)
6988 SELECT 'OrderID', 'OrderID', 'SubOrder'
6989
6990 INSERT INTO #Ref(ReferenceType)
6991 VALUES ('OrderID')
6992
6993 END
6994
6995IF EXISTS(SELECT 1 FROM #Column AS C WHERE C.CName = 'PO')
6996 BEGIN
6997 INSERT INTO [#WantedRefTypes] (RefTypeInDestTable,RefTypeInSourceTable,RefSubTypeInSourceTable)
6998 SELECT 'PO', 'PO', 'SubOrder'
6999
7000 INSERT INTO #Ref(ReferenceType)
7001 VALUES ('PO')
7002
7003 END
7004
7005IF EXISTS(SELECT 1 FROM #Column AS C WHERE C.CName = 'PRO')
7006 BEGIN
7007 INSERT INTO [#WantedRefTypes] (RefTypeInDestTable,RefTypeInSourceTable,RefSubTypeInSourceTable)
7008 SELECT 'PRO', 'PRO', 'SubOrder'
7009
7010 INSERT INTO #Ref(ReferenceType)
7011 VALUES ('PRO')
7012
7013 END
7014
7015IF EXISTS(SELECT 1 FROM #Column AS C WHERE C.CName = 'PU')
7016 BEGIN
7017 INSERT INTO [#WantedRefTypes] (RefTypeInDestTable,RefTypeInSourceTable,RefSubTypeInSourceTable)
7018 SELECT 'PU', 'PU', 'SubOrder'
7019
7020 INSERT INTO #Ref(ReferenceType)
7021 VALUES ('PU')
7022
7023 END
7024
7025IF EXISTS(SELECT 1 FROM #Column AS C WHERE C.CName = 'SEAL')
7026 BEGIN
7027 INSERT INTO [#WantedRefTypes] (RefTypeInDestTable,RefTypeInSourceTable,RefSubTypeInSourceTable)
7028 SELECT 'SEAL', 'SEAL', 'SubOrder'
7029
7030 INSERT INTO #Ref(ReferenceType)
7031 VALUES ('SEAL')
7032 END
7033
7034IF EXISTS(SELECT 1 FROM #Column AS C WHERE C.CName = 'SHID')
7035 BEGIN
7036 INSERT INTO [#WantedRefTypes] (RefTypeInDestTable,RefTypeInSourceTable,RefSubTypeInSourceTable)
7037 SELECT 'SHID', 'SHID', 'SubOrder'
7038
7039 INSERT INTO #Ref(ReferenceType)
7040 VALUES ('SHID')
7041
7042 END
7043
7044IF EXISTS(SELECT 1 FROM #Column AS C WHERE C.CName = 'SHIPWITH')
7045 BEGIN
7046 INSERT INTO [#WantedRefTypes] (RefTypeInDestTable,RefTypeInSourceTable,RefSubTypeInSourceTable)
7047 SELECT 'SHIPWITH', 'SHIPWITH', 'SubOrder'
7048
7049 INSERT INTO #Ref(ReferenceType)
7050 VALUES ('SHIPWITH')
7051
7052 END
7053
7054 --PRINT 'LOAD Single Reference Numbers'
7055
7056 -- Insert single reference numbers
7057 INSERT INTO [#Ref] (Ref_RecordID,ReferenceType,ReferenceSubType,ReferenceNumber)
7058SELECT DISTINCT
7059 R.RecordID,
7060 WRT.RefTypeInDestTable,
7061 '', --4/20/11 - SUGGMIC - Excel with inrepret a bunch of numbers with no space inbetween as a number vs a string, space fixes it
7062 REPLACE(DR.ReferenceNumber, ',', ', ')
7063FROM #Row AS R
7064INNER JOIN COSGroup AS COSG WITH (NOLOCK)
7065 ON R.COSGroupID = COSG.COSGroupID
7066INNER JOIN COService AS Everybody WITH (NOLOCK)
7067 ON Everybody.COSGroupID = COSG.COSGroupID AND Everybody.HBLFlag = 1
7068INNER JOIN COServiceReference AS C WITH(NOLOCK)
7069 ON Everybody.COServiceID = C.COServiceID
7070INNER JOIN [#WantedRefTypes] AS WRT
7071 ON C.ReferenceType = WRT.RefTypeInSourceTable
7072 AND C.ReferenceSubType = WRT.RefSubTypeInSourceTable
7073INNER JOIN NTSR.dbo.DimReference AS DR WITH(NOLOCK)
7074 ON C.KeyReferenceID = DR.KeyReferenceID
7075INNER JOIN OrderParty AS OP WITH(NOLOCK)
7076 ON C.OrderPartyID = OP.OrderPartyID
7077INNER JOIN #UserCCodes AS CC
7078 ON OP.PartyCode = CC.CompanyCode
7079WHERE R.ShipmentMode = 'Ocean' AND R.SourceTypeID = 7
7080
7081UNION ALL
7082
7083SELECT DISTINCT
7084 R.RecordID,
7085 WRT.RefTypeInDestTable,
7086 '', --4/20/11 - SUGGMIC - Excel with inrepret a bunch of numbers with no space inbetween as a number vs a string, space fixes it
7087 REPLACE(DR.ReferenceNumber, ',', ', ')
7088FROM #Row AS R
7089INNER JOIN COServiceReference AS C WITH(NOLOCK)
7090 ON R.COServiceID = C.COServiceID
7091INNER JOIN [#WantedRefTypes] AS WRT
7092 ON C.ReferenceType = WRT.RefTypeInSourceTable
7093 AND C.ReferenceSubType = WRT.RefSubTypeInSourceTable
7094INNER JOIN NTSR.dbo.DimReference AS DR WITH(NOLOCK)
7095 ON C.KeyReferenceID = DR.KeyReferenceID
7096INNER JOIN OrderParty AS OP WITH(NOLOCK)
7097 ON C.OrderPartyID = OP.OrderPartyID
7098INNER JOIN #UserCCodes AS CC
7099 ON OP.PartyCode = CC.CompanyCode
7100WHERE R.ShipmentMode <> 'Ocean' OR R.SourceTypeID <> 7
7101
7102UNION ALL
7103
7104SELECT DISTINCT
7105 R.RecordID,
7106 WRT.RefTypeInDestTable,
7107 '',
7108 --4/20/11 - SUGGMIC - Excel with inrepret a bunch of numbers with no space inbetween as a number vs a string, space fixes it
7109 REPLACE(DR.ReferenceNumber, ',', ', ')
7110FROM #Row AS R
7111INNER JOIN COServiceReference AS C WITH(NOLOCK)
7112 ON R.COServiceID = C.COServiceID
7113INNER JOIN [#WantedRefTypes] AS WRT
7114 ON C.ReferenceType = WRT.RefTypeInSourceTable
7115 AND C.ReferenceSubType = WRT.RefSubTypeInSourceTable
7116INNER JOIN NTSR.dbo.DimReference AS DR WITH(NOLOCK)
7117 ON C.KeyReferenceID = DR.KeyReferenceID
7118WHERE C.OrderPartyID = -1
7119
7120UNION ALL
7121-- Detail Reference
7122SELECT DISTINCT
7123 R.RecordID,
7124 WRT.RefTypeInDestTable,
7125 '',
7126 --4/20/11 - SUGGMIC - Excel with inrepret a bunch of numbers with no space inbetween as a number vs a string, space fixes it
7127 REPLACE(DR.ReferenceNumber, ',', ', ')
7128FROM #Row AS R
7129INNER JOIN COSDetailReference AS CDR WITH(NOLOCK)
7130 ON R.COSDetailID = CDR.COSDetailID
7131INNER JOIN [#WantedRefTypes] AS WRT
7132 ON CDR.ReferenceType = WRT.RefTypeInSourceTable
7133 AND CDR.ReferenceSubType = WRT.RefSubTypeInSourceTable
7134INNER JOIN NTSR.dbo.DimReference AS DR WITH(NOLOCK)
7135 ON CDR.KeyReferenceID = DR.KeyReferenceID
7136OPTION(LOOP JOIN)
7137
7138
7139--Here is some MBOL GFO fun - we're taking the parent MBOL when applicable! Schottler or Suggs did this, FYI.
7140INSERT INTO [#Ref] (Ref_RecordID,ReferenceType,ReferenceSubType,ReferenceNumber)
7141SELECT DISTINCT
7142 R.RecordID,
7143 --WRT.RefTypeInDestTable,
7144 'MBOL',
7145 '',
7146 REPLACE(DR.ReferenceNumber, ',', ', ')
7147FROM #Row AS R
7148INNER JOIN COSGroup AS COSG WITH (NOLOCK)
7149 ON R.COSGroupID = COSG.COSGroupID
7150INNER JOIN COService AS Everybody WITH (NOLOCK)
7151 ON Everybody.COSGroupID = COSG.COSGroupID AND Everybody.HBLFlag = 0
7152INNER JOIN COServiceReference AS C WITH(NOLOCK)
7153 ON Everybody.COServiceID = C.COServiceID
7154INNER JOIN NTSR.dbo.DimReference AS DR WITH(NOLOCK)
7155 ON C.KeyReferenceID = DR.KeyReferenceID
7156WHERE C.OrderPartyID = -1 AND C.ReferenceType = 'MBOL' AND R.SourceTypeID = 7 AND R.HBLFlag = 1
7157
7158
7159 -- Set AirlineWaybill reference to HBOL if service level is S-Air
7160 UPDATE R
7161 SET R.ReferenceNumber = (
7162 SELECT TOP 1 RF.ReferenceNumber FROM [#Ref] RF
7163 INNER JOIN #Row RW ON RF.Ref_RecordID = RW.RecordID
7164 WHERE RF.ReferenceType='HBOL' AND RW.ServiceLevel = 'S-AIR' AND RF.Ref_RecordID = RW2.RecordID
7165 )
7166 FROM [#Ref] R INNER JOIN #Row RW2 ON R.Ref_RecordID = RW2.RecordID
7167 WHERE R.ReferenceType = 'AirlineWayBill' AND
7168 Exists(
7169 SELECT 1 FROM [#Ref] RF
7170 INNER JOIN #Row RW ON RF.Ref_RecordID = RW.RecordID
7171 WHERE RF.ReferenceType='HBOL' AND RW.ServiceLevel = 'S-AIR' AND RF.Ref_RecordID = RW2.RecordID
7172 )
7173
7174
7175 --PRINT 'Loading Ref Buckets'
7176
7177 CREATE TABLE #WantedRefBucketTypes
7178 (
7179 RefSubTypeInSourceTable VARCHAR(50),
7180 RefSubTypeInDestTable VARCHAR(50)
7181 )
7182
7183 --PRINT 'Exists PayerRefNums?'
7184
7185 IF EXISTS(SELECT 1 FROM #Column AS C WHERE C.CName = 'PayerRefNums')
7186 BEGIN
7187 INSERT INTO #WantedRefBucketTypes(RefSubTypeInSourceTable,RefSubTypeInDestTable)
7188 SELECT 'Payer', 'Payer'
7189 END
7190
7191 --PRINT 'Exists OrigRefNums?'
7192
7193 IF EXISTS(SELECT 1 FROM #Column AS C WHERE C.CName = 'OrigRefNums')
7194 BEGIN
7195INSERT INTO #WantedRefBucketTypes(RefSubTypeInSourceTable,RefSubTypeInDestTable)
7196 SELECT 'Origin', 'Origin'
7197 END
7198
7199 --PRINT 'Exists DestRefNums?'
7200
7201 IF EXISTS(SELECT 1 FROM #Column AS C WHERE C.CName = 'DestRefNums')
7202 BEGIN
7203 INSERT INTO #WantedRefBucketTypes(RefSubTypeInSourceTable,RefSubTypeInDestTable)
7204 SELECT 'Destination', 'Destination'
7205 END
7206
7207 --PRINT 'Exists ShipmentRefNums?'
7208
7209 IF EXISTS(SELECT 1 FROM #Column AS C WHERE C.CName = 'ShipmentRefNums')
7210 BEGIN
7211 INSERT INTO #WantedRefBucketTypes(RefSubTypeInSourceTable,RefSubTypeInDestTable)
7212 SELECT 'SubOrder', 'Shipment'
7213 UNION ALL
7214 SELECT 'Load', 'Shipment'
7215 UNION ALL
7216 SELECT 'Shipment', 'Shipment' -- 07/24/2009 GFS
7217 END
7218
7219 --PRINT 'LOAD Ref Buckets'
7220
7221 IF EXISTS(SELECT 1 FROM #WantedRefBucketTypes)
7222 BEGIN
7223 INSERT INTO [#Ref] (Ref_RecordID,ReferenceType,ReferenceSubType,ReferenceNumber)
7224 SELECT DISTINCT
7225 R.RecordID,
7226 T.RefSubTypeInDestTable + ' ' + RT.ReferenceType,
7227 T.RefSubTypeInDestTable,
7228 DR.ReferenceNumber
7229 FROM #Row AS R
7230 INNER JOIN COServiceReference AS C WITH(NOLOCK)
7231 ON R.COServiceID = C.COServiceID
7232 INNER JOIN #WantedRefBucketTypes AS T
7233 ON C.ReferenceSubType = T.RefSubTypeInSourceTable
7234 INNER JOIN [#RefType] AS RT
7235 ON C.ReferenceType = RT.ReferenceType
7236 INNER JOIN NTSR.dbo.DimReference AS DR WITH(NOLOCK)
7237 ON C.KeyReferenceID = DR.KeyReferenceID
7238
7239 UNION ALL
7240
7241 SELECT DISTINCT
7242 R.RecordID,
7243 T.RefSubTypeInDestTable + ' ' + C.ReferenceType,
7244 T.RefSubTypeInDestTable,
7245 DR.ReferenceNumber
7246 FROM #Row AS R
7247 INNER JOIN COSDetailReference AS C WITH(NOLOCK)
7248 ON R.COSDetailID = C.COSDetailID
7249 INNER JOIN #WantedRefBucketTypes AS T
7250 ON C.ReferenceSubType = T.RefSubTypeInSourceTable
7251 INNER JOIN NTSR.dbo.DimReference AS DR WITH(NOLOCK)
7252 ON C.KeyReferenceID = DR.KeyReferenceID
7253 END
7254
7255 --PRINT 'Update Ref.DeleteFlg = 1'
7256
7257 UPDATE R
7258 SET DeleteFlg = 1
7259 FROM #Ref AS R
7260 WHERE EXISTS
7261 (
7262 SELECT 1
7263 FROM #Ref AS R2
7264 WHERE R.Ref_RecordID = R2.Ref_RecordID AND R.ReferenceType = R2.ReferenceType
7265 GROUP BY R2.Ref_RecordID
7266 HAVING COUNT(1) > 1
7267 )
7268
7269 --PRINT 'INSERT Ref.COUNT(1) > 1'
7270
7271 INSERT INTO #Ref(Ref_RecordID, ReferenceType,ReferenceSubType,ReferenceNumber)
7272 SELECT DISTINCT
7273 R.Ref_RecordID,
7274 R.ReferenceType,
7275 R.ReferenceSubType,
7276 (
7277 SELECT R2.ReferenceNumber + ', '
7278 FROM #Ref AS R2
7279 WHERE
7280 R.Ref_RecordID = R2.Ref_RecordID
7281 AND R.ReferenceType = R2.ReferenceType
7282 FOR XML PATH('')
7283 )
7284
7285 FROM #Ref AS R
7286 WHERE R.DeleteFlg = 1
7287 GROUP BY R.Ref_RecordID, R.ReferenceType, R.ReferenceSubType
7288
7289 --PRINT 'Delete Ref.DeleteFlg = 1'
7290
7291 DELETE FROM #Ref WHERE DeleteFlg = 1
7292
7293 -- OK02142008========================================================================
7294 -- Load #ItemRefs
7295 -- ==================================================================================
7296
7297 --PRINT 'Loading ItemRefs'
7298
7299 CREATE TABLE #ItemRefTypes
7300 (
7301 RefTypeInSourceTable VARCHAR(50),
7302 RefTypeInColumnTable VARCHAR(50)
7303 )
7304
7305 --PRINT 'Exists UPC?'
7306
7307 IF EXISTS(SELECT 1 FROM #Column AS C WHERE C.CName = 'UPC')
7308 BEGIN
7309INSERT INTO [#ItemRefTypes] (RefTypeInSourceTable,RefTypeInColumnTable)
7310 SELECT 'UPC', 'UPC'
7311
7312 INSERT INTO #ItemRef(ItemReferenceType)
7313 VALUES ('UPC')
7314 END
7315
7316 --PRINT 'Exists NMFC?'
7317
7318 IF EXISTS(SELECT 1 FROM #Column AS C WHERE C.CName = 'NMFC')
7319 BEGIN
7320 INSERT INTO [#ItemRefTypes] (RefTypeInSourceTable,RefTypeInColumnTable)
7321 SELECT 'NMFC', 'NMFC'
7322
7323 INSERT INTO #ItemRef(ItemReferenceType)
7324 VALUES ('NMFC')
7325 END
7326
7327 --PRINT 'Exists CustSpecific1?'
7328
7329 IF EXISTS(SELECT 1 FROM #Column AS C WHERE C.CName = 'CustSpecific1')
7330 BEGIN
7331 INSERT INTO [#ItemRefTypes] (RefTypeInSourceTable,RefTypeInColumnTable)
7332 SELECT 'CSP1', 'CustSpecific1'
7333
7334 INSERT INTO #ItemRef(ItemReferenceType)
7335 VALUES ('CustSpecific1')
7336 END
7337
7338 --PRINT 'Exists CustSpecific2?'
7339
7340 IF EXISTS(SELECT 1 FROM #Column AS C WHERE C.CName = 'CustSpecific2')
7341 BEGIN
7342 INSERT INTO [#ItemRefTypes] (RefTypeInSourceTable,RefTypeInColumnTable)
7343 SELECT 'CSP2', 'CustSpecific2'
7344
7345 INSERT INTO #ItemRef(ItemReferenceType)
7346 VALUES ('CustSpecific2')
7347 END
7348
7349 --PRINT 'Exists ProductCode?'
7350
7351 IF EXISTS(SELECT 1 FROM #Column AS C WHERE C.CName = 'ProductCode')
7352 BEGIN
7353 INSERT INTO [#ItemRefTypes] (RefTypeInSourceTable,RefTypeInColumnTable)
7354 SELECT 'ProductCode', 'ProductCode'
7355
7356 INSERT INTO #ItemRef(ItemReferenceType)
7357 VALUES ('ProductCode')
7358 END
7359
7360 --PRINT 'Exists PLU?'
7361
7362 IF EXISTS(SELECT 1 FROM #Column AS C WHERE C.CName = 'PLU')
7363 BEGIN
7364 INSERT INTO [#ItemRefTypes] (RefTypeInSourceTable,RefTypeInColumnTable)
7365 SELECT 'PLU', 'PLU'
7366
7367 INSERT INTO #ItemRef(ItemReferenceType)
7368 VALUES ('PLU')
7369 END
7370
7371 --PRINT 'Exists EAN?'
7372
7373 IF EXISTS(SELECT 1 FROM #Column AS C WHERE C.CName = 'EAN')
7374 BEGIN
7375 INSERT INTO [#ItemRefTypes] (RefTypeInSourceTable,RefTypeInColumnTable)
7376 SELECT 'EAN', 'EAN'
7377
7378 INSERT INTO #ItemRef(ItemReferenceType)
7379 VALUES ('EAN')
7380 END
7381
7382 --PRINT 'Exists HTCode?'
7383
7384 IF EXISTS(SELECT 1 FROM #Column AS C WHERE C.CName = 'HTCode')
7385 BEGIN
7386 INSERT INTO [#ItemRefTypes] (RefTypeInSourceTable,RefTypeInColumnTable)
7387 SELECT 'HTCode', 'HTCode'
7388
7389 INSERT INTO #ItemRef(ItemReferenceType)
7390 VALUES ('HTCode')
7391 END
7392
7393 --PRINT 'Exists VendorPO?'
7394
7395 IF EXISTS(SELECT 1 FROM #Column AS C WHERE C.CName = 'VendorPO')
7396 BEGIN
7397 INSERT INTO [#ItemRefTypes] (RefTypeInSourceTable,RefTypeInColumnTable)
7398 SELECT 'VendorPO', 'VendorPO'
7399
7400 INSERT INTO #ItemRef(ItemReferenceType)
7401 VALUES ('VendorPO')
7402 END
7403
7404 --PRINT 'Exists JobNum?'
7405
7406 IF EXISTS(SELECT 1 FROM #Column AS C WHERE C.CName = 'JobNum')
7407 BEGIN
7408 INSERT INTO [#ItemRefTypes] (RefTypeInSourceTable,RefTypeInColumnTable)
7409 SELECT 'JobNum', 'JobNum'
7410
7411 INSERT INTO #ItemRef(ItemReferenceType)
7412 VALUES ('JobNum')
7413 END
7414
7415 -- 04/11/2008 GANASAD Added PO Number field
7416 --PRINT 'Exists PONum?'
7417 IF EXISTS(SELECT 1 FROM #Column AS C WHERE C.CName = 'PONum')
7418 BEGIN
7419 INSERT INTO [#ItemRefTypes] (RefTypeInSourceTable,RefTypeInColumnTable)
7420 SELECT 'PO', 'PONum'
7421
7422 INSERT INTO #ItemRef(ItemReferenceType)
7423 VALUES ('PONum')
7424 END
7425
7426 IF EXISTS(SELECT 1 FROM #Column AS C WHERE C.CName = 'LotNumber')
7427 BEGIN
7428 INSERT INTO [#ItemRefTypes] (RefTypeInSourceTable,RefTypeInColumnTable)
7429 SELECT 'LotNumber', 'LotNumber'
7430
7431 INSERT INTO #ItemRef(ItemReferenceType)
7432 VALUES ('LotNumber')
7433 END
7434
7435 --PRINT 'Insert individual item refs'
7436
7437 -- Insert individual item refs
7438 INSERT INTO #ItemRef (ItemRef_RecordID,ItemRef_ItemID,ItemReferenceType,ItemReferenceSubType,ItemReferenceNumber)
7439 SELECT
7440 R.RecordID,
7441 I.ItemID AS ItemRef_ItemID,
7442 --I.[COItemID] AS ItemRef_ItemID,
7443 IRT.RefTypeInColumnTable,
7444 '',
7445 DR.ReferenceNumber
7446 FROM #Row AS R
7447-- INNER JOIN COSDetail AS D WITH(NOLOCK)
7448-- ON R.COServiceID = D.COServiceID
7449/*NEW OR CHANGED Jeremy Dixon 1/2014*/
7450 --INNER JOIN COItem AS I WITH(NOLOCK)
7451 -- ON R.COSDetailID = I.COSDetailID
7452 /*NEW OR CHANGED Jeremy Dixon 1/2014*/
7453 INNER JOIN #Item I
7454 ON I.Item_RecordID = R.RecordID
7455 INNER JOIN COItemReference AS IR WITH(NOLOCK)
7456 ON I.ItemID = IR.COItemID
7457 INNER JOIN #ItemRefTypes AS IRT
7458 ON IR.ReferenceType = IRT.RefTypeInSourceTable
7459 INNER JOIN NTSR.dbo.DimReference AS DR WITH(NOLOCK)
7460 ON IR.KeyReferenceID = DR.KeyReferenceID
7461 --OPTION (LOOP JOIN)
7462 --PRINT 'Insert item bucket'
7463
7464 -- Item Bucket
7465 IF EXISTS(SELECT 1 FROM #Column AS C WITH(NOLOCK) WHERE C.CName = 'ItemRefNums')
7466 BEGIN
7467 INSERT INTO #ItemRef
7468 (
7469 ItemRef_RecordID,
7470 ItemRef_ItemID,
7471 ItemReferenceType,
7472 ItemReferenceSubType,
7473 ItemReferenceNumber
7474 )
7475
7476 SELECT
7477 R.RecordID,
7478 I.[COItemID] AS ItemRef_ItemID,
7479 'Item ' + RT.ReferenceType,
7480 'Item',
7481 DR.ReferenceNumber
7482 FROM #Row AS R
7483 INNER JOIN COItem AS I WITH(NOLOCK)
7484 ON R.COSDetailID = I.COSDetailID
7485 INNER JOIN COItemReference AS IR WITH(NOLOCK)
7486 ON I.COItemID = IR.COItemID
7487 INNER JOIN [#Reftype] AS RT
7488 ON IR.ReferenceType = RT.ReferenceType
7489 INNER JOIN NTSR.dbo.DimReference AS DR WITH(NOLOCK)
7490 ON IR.KeyReferenceID = DR.KeyReferenceID
7491 OPTION(LOOP JOIN)
7492
7493 --RESCEMI - let's just rename CommercialInvoiceNum to CIN. Why not.
7494 UPDATE I
7495 SET ItemReferenceType = 'Item CIN'
7496 FROM #ItemRef AS I
7497 WHERE I.ItemReferenceType = 'Item CommercialInvoiceNum'
7498
7499 --PRINT 'Update ItemRef.DeleteFlg'
7500
7501 UPDATE I
7502 SET ItemDeleteFlg = 1
7503 FROM #ItemRef AS I
7504 WHERE EXISTS
7505 (
7506 SELECT 1
7507 FROM #ItemRef AS I2
7508 WHERE I.ItemRef_RecordID = I2.ItemRef_RecordID AND I.[ItemRef_ItemID]=I2.[ItemRef_ItemID] AND I.ItemReferenceType = I2.ItemReferenceType
7509 GROUP BY I2.ItemRef_RecordID, I2.ItemRef_ItemID
7510 HAVING COUNT(1) > 1
7511 )
7512
7513 --PRINT 'Insert ItemRef.COUNT(1) > 1'
7514
7515 INSERT INTO #ItemRef(ItemRef_RecordID,ItemRef_ItemID,ItemReferenceType,ItemReferenceSubType,ItemReferenceNumber)
7516 SELECT
7517 I.ItemRef_RecordID,
7518 I.[ItemRef_ItemID],
7519 I.ItemReferenceType,
7520 I.ItemReferenceSubType,
7521 (
7522 SELECT I2.ItemReferenceNumber + ', '
7523 FROM #ItemRef AS I2
7524 WHERE
7525 I.ItemRef_RecordID = I2.ItemRef_RecordID AND I.ItemRef_ItemID = I2.[ItemRef_ItemID]
7526 AND I.ItemReferenceType = I2.ItemReferenceType
7527 FOR XML PATH('')
7528 )
7529 FROM #ItemRef AS I
7530 WHERE I.ItemDeleteFlg = 1
7531 GROUP BY I.ItemRef_RecordID, I.[ItemRef_ItemID], I.ItemReferenceType, I.ItemReferenceSubType
7532
7533 --PRINT 'Delete ItemRef.DeleteFlg = 1'
7534
7535 DELETE FROM #ItemRef WHERE ItemDeleteFlg = 1
7536 END
7537
7538 -- ========================================================================================================
7539 -- CHARGES START
7540 -- ========================================================================================================
7541--DO I NEED TO ADD OPTION LOOP JOINS?
7542IF EXISTS(SELECT TOP 1 1 FROM #Column AS C WITH (NOLOCK) WHERE C.CName IN ('AgentFee', 'FreightCharge', 'EndCustFreightCharge', 'AccessorialOtherCharge', 'EndCustAccessorialCharge', 'TotalCharges', 'EndCustTotalCharges', 'SourceCurrencyCode', 'AccessorialOtherDetails.*', 'EndCustAccessorialDetails.*'))
7543BEGIN
7544 --PULL IN ALL FINANCIAL DATA
7545 INSERT INTO #TEMP_CHARGES (RecordID, ProcessRollup, ProcessBreakdown, MoneyType, [Description], Amount, AccessorialFlg, FinancialType, SourceCurrencyCode)
7546 SELECT
7547 R.RecordID,
7548 CASE WHEN MultiLegFlg = 0 OR @SummarizeShipment = 0 THEN 1 ELSE 0 END,
7549 CASE WHEN MultiLegFlg = 1 AND M.LoadNumber = R.LoadNumber AND @SummarizeShipment = 1 THEN 1 ELSE 0 END,
7550 D.MoneyType,
7551 D.[Description],
7552 D.Amount,
7553 D.AccessorialFlg,
7554 D.FinancialType,
7555 D.SourceCurrencyCode
7556 FROM #Row R
7557 INNER JOIN COSDetailMoney D WITH(NOLOCK) ON R.COSDetailID = D.COSDetailID
7558 INNER JOIN [Money] M WITH(NOLOCK) ON D.MoneyID = M.MoneyID
7559 INNER JOIN OrderParty P WITH(NOLOCK) ON D.OrderPartyID = P.OrderPartyID
7560 WHERE EXISTS(SELECT TOP 1 1 FROM #UserCCodes U WHERE P.PartyCode = U.CompanyCode)
7561 --IS THIS NEEDED?
7562 --OPTION(LOOP JOIN)
7563
7564 --AGENT FEES
7565 IF EXISTS (SELECT TOP 1 1 FROM #Column AS C WITH (NOLOCK) WHERE C.CName = 'AgentFee')
7566 BEGIN
7567 INSERT INTO #AgentFee (AgentFee_RecordID, AgentFee)
7568 SELECT
7569 RecordID,
7570 SUM(C.Amount)
7571 FROM #TEMP_CHARGES C
7572 WHERE ProcessRollup = 1 AND C.MoneyType = 'Agent Fee'
7573 GROUP BY RecordID
7574
7575 INSERT INTO #AgentFee (AgentFee_RecordID, AgentFee)
7576 SELECT
7577 RecordID,
7578 SUM(C.Amount)
7579 FROM #TEMP_CHARGES C
7580 WHERE ProcessBreakdown = 1 AND C.MoneyType = 'Agent Fee'
7581 GROUP BY RecordID
7582 END
7583
7584 --FREIGHT CHARGES
7585 IF EXISTS (SELECT TOP 1 1 FROM #Column AS C WITH (NOLOCK) WHERE C.CName = 'FreightCharge')
7586 BEGIN
7587 INSERT INTO #FreightCharge (FreightCharge_RecordID, FreightCharge)
7588 SELECT
7589 RecordID,
7590 SUM(CASE C.FinancialType WHEN 'ActCharge' THEN C.Amount ELSE -1 * C.Amount END)
7591 FROM #TEMP_CHARGES C
7592 WHERE ProcessRollup = 1 AND C.MoneyType = '400' AND C.AccessorialFlg = 0 AND C.FinancialType IN ('ActCharge', 'ActCost')
7593 GROUP BY RecordID
7594
7595 INSERT INTO #FreightCharge (FreightCharge_RecordID, FreightCharge)
7596 SELECT
7597 RecordID,
7598 SUM(CASE C.FinancialType WHEN 'ActCharge' THEN C.Amount ELSE -1 * C.Amount END)
7599 FROM #TEMP_CHARGES C
7600 WHERE ProcessBreakdown = 1 AND C.MoneyType = '400' AND C.AccessorialFlg = 0 AND C.FinancialType IN ('ActCharge', 'ActCost')
7601 GROUP BY RecordID
7602 END
7603
7604 --END CUSTOMER FREIGHT CHARGES
7605 IF EXISTS (SELECT TOP 1 1 FROM #Column AS C WITH (NOLOCK) WHERE C.CName = 'EndCustFreightCharge')
7606 BEGIN
7607 INSERT INTO #EndCustFreightCharge (EndCustFreightCharge_RecordID, EndCustFreightCharge)
7608 SELECT
7609 RecordID,
7610 SUM(C.Amount)
7611 FROM #TEMP_CHARGES C
7612 WHERE ProcessRollup = 1 AND C.FinancialType = 'ECC' AND C.AccessorialFlg = 0
7613 GROUP BY RecordID
7614
7615 INSERT INTO #EndCustFreightCharge (EndCustFreightCharge_RecordID, EndCustFreightCharge)
7616 SELECT
7617 RecordID,
7618 SUM(C.Amount)
7619 FROM #TEMP_CHARGES C
7620 WHERE ProcessBreakdown = 1 AND C.FinancialType = 'ECC' AND C.AccessorialFlg = 0
7621 GROUP BY RecordID
7622 END
7623
7624 --ACCESSORIAL OTHER CHARGE
7625 IF EXISTS (SELECT TOP 1 1 FROM #Column AS C WITH (NOLOCK) WHERE C.CName = 'AccessorialOtherCharge')
7626 BEGIN
7627 INSERT INTO #AccessorialOtherCharge (AccessorialOtherCharge_RecordID, AccessorialOtherCharge)
7628 SELECT
7629 RecordID,
7630 SUM(CASE C.FinancialType WHEN 'ActCharge' THEN C.Amount ELSE -1 * C.Amount END)
7631 FROM #TEMP_CHARGES C
7632 WHERE ProcessRollup = 1 AND C.AccessorialFlg = 1 AND C.FinancialType IN ('ActCharge', 'ActCost')
7633 GROUP BY RecordID
7634
7635 INSERT INTO #AccessorialOtherCharge (AccessorialOtherCharge_RecordID, AccessorialOtherCharge)
7636 SELECT
7637 RecordID,
7638 SUM(CASE C.FinancialType WHEN 'ActCharge' THEN C.Amount ELSE -1 * C.Amount END)
7639 FROM #TEMP_CHARGES C
7640 WHERE ProcessBreakdown = 1 AND C.AccessorialFlg = 1 AND C.FinancialType IN ('ActCharge', 'ActCost')
7641 GROUP BY RecordID
7642 END
7643
7644 --END ACCESSORIAL OTHER CHARGE
7645 IF EXISTS (SELECT TOP 1 1 FROM #Column AS C WITH (NOLOCK) WHERE C.CName = 'EndCustAccessorialCharge')
7646 BEGIN
7647 INSERT INTO #EndCustAccessorialCharge (EndCustAccessorialCharge_RecordID, EndCustAccessorialCharge)
7648 SELECT
7649 RecordID,
7650 SUM(C.Amount)
7651 FROM #TEMP_CHARGES C
7652 WHERE ProcessRollup = 1 AND C.AccessorialFlg = 1 AND C.FinancialType = 'ECC'
7653 GROUP BY RecordID
7654
7655 INSERT INTO #EndCustAccessorialCharge (EndCustAccessorialCharge_RecordID, EndCustAccessorialCharge)
7656 SELECT
7657 RecordID,
7658 SUM(C.Amount)
7659 FROM #TEMP_CHARGES C
7660 WHERE ProcessBreakdown = 1 AND C.AccessorialFlg = 1 AND C.FinancialType = 'ECC'
7661 GROUP BY RecordID
7662 END
7663
7664 --TOTAL CHARGES
7665 IF EXISTS (SELECT TOP 1 1 FROM #Column AS C WITH (NOLOCK) WHERE C.CName = 'TotalCharges')
7666 BEGIN
7667 INSERT INTO #TotalCharge (TotalCharge_RecordID, TotalCharges)
7668 SELECT
7669 RecordID,
7670 SUM(CASE C.FinancialType WHEN 'ActCharge' THEN C.Amount ELSE -1 * C.Amount END)
7671 FROM #TEMP_CHARGES C
7672 WHERE ProcessRollup = 1 AND C.MoneyType <> 'Agent Fee' AND C.FinancialType IN ('ActCharge', 'ActCost')
7673 GROUP BY RecordID
7674
7675 INSERT INTO #TotalCharge (TotalCharge_RecordID, TotalCharges)
7676 SELECT
7677 RecordID,
7678 SUM(CASE C.FinancialType WHEN 'ActCharge' THEN C.Amount ELSE -1 * C.Amount END)
7679 FROM #TEMP_CHARGES C
7680 WHERE ProcessBreakdown = 1 AND C.MoneyType <> 'Agent Fee' AND C.FinancialType IN ('ActCharge', 'ActCost')
7681 GROUP BY RecordID
7682 END
7683
7684 --TOTAL END CUSTOMER CHARGES
7685 IF EXISTS(SELECT TOP 1 1 FROM #Column AS C WITH(NOLOCK) WHERE C.CName = 'EndCustTotalCharges')
7686 BEGIN
7687 INSERT INTO #EndCustTotalCharges (EndCustTotalCharges_RecordID, EndCustTotalCharges)
7688 SELECT
7689 RecordID,
7690 SUM(C.Amount)
7691 FROM #TEMP_CHARGES C
7692 WHERE ProcessRollup = 1 AND C.FinancialType = 'ECC'
7693 GROUP BY RecordID
7694
7695 INSERT INTO #EndCustTotalCharges (EndCustTotalCharges_RecordID, EndCustTotalCharges)
7696 SELECT
7697 RecordID,
7698 SUM(C.Amount)
7699 FROM #TEMP_CHARGES C
7700 WHERE ProcessBreakdown = 1 AND C.FinancialType = 'ECC'
7701 GROUP BY RecordID
7702 END
7703
7704 --SOURCE CURRENCY CODE
7705 IF EXISTS(SELECT TOP 1 1 FROM #Column AS C WITH(NOLOCK) WHERE C.CName = 'SourceCurrencyCode')
7706 BEGIN
7707 INSERT INTO #SourceCurrencyCode (SourceCurrencyCode_RecordID, SourceCurrencyCode)
7708 SELECT
7709 RecordID,
7710 C.SourceCurrencyCode
7711 FROM #TEMP_CHARGES C
7712 WHERE ProcessRollUp = 1
7713 GROUP BY RecordID, C.SourceCurrencyCode
7714
7715 INSERT INTO #SourceCurrencyCode (SourceCurrencyCode_RecordID, SourceCurrencyCode)
7716 SELECT
7717 RecordID,
7718 C.SourceCurrencyCode
7719 FROM #TEMP_CHARGES C
7720 WHERE ProcessBreakdown = 1 AND C.FinancialType = 'ECC'
7721 GROUP BY RecordID, C.SourceCurrencyCode
7722
7723 END
7724
7725 --ACCESSORIALS
7726 IF EXISTS(SELECT TOP 1 1 FROM #Column AS C WITH(NOLOCK) WHERE C.CName IN ('AccessorialOtherDetails.*', 'EndCustAccessorialDetails.*'))
7727 BEGIN
7728 INSERT INTO #AccessorialChargeDescription (AccessorialChargeDescription_RecordID, [Description], Amount, AccessorialChargeFinancialType)
7729 SELECT
7730 RecordID,
7731 CASE FinancialType
7732 WHEN 'ECC' THEN 'End Customer ' + LEFT(C.[Description], 115)
7733 WHEN 'ActCost' THEN 'Payable ' + LEFT(C.[Description], 120)
7734 ELSE LEFT(C.[Description], 128)
7735 END,
7736 SUM(CASE C.FinancialType WHEN 'ActCost' THEN -1 * C.Amount ELSE C.Amount END),
7737 CASE C.FinancialType WHEN 'ActCost' THEN 'ActCharge' ELSE C.FinancialType END
7738 FROM #TEMP_CHARGES C
7739 WHERE ProcessRollup = 1 AND C.AccessorialFlg = 1
7740 GROUP BY C.RecordID, C.[Description], C.FinancialType
7741
7742 INSERT INTO #AccessorialChargeDescription (AccessorialChargeDescription_RecordID, [Description], Amount, AccessorialChargeFinancialType)
7743 SELECT
7744 RecordID,
7745 CASE FinancialType
7746 WHEN 'ECC' THEN 'End Customer ' + LEFT(C.[Description], 115)
7747 WHEN 'ActCost' THEN 'Payable ' + LEFT(C.[Description], 120)
7748 ELSE LEFT(C.[Description], 128)
7749 END,
7750 SUM(CASE C.FinancialType WHEN 'ActCost' THEN -1 * C.Amount ELSE C.Amount END),
7751 CASE C.FinancialType WHEN 'ActCost' THEN 'ActCharge' ELSE C.FinancialType END
7752 FROM #TEMP_CHARGES C
7753 WHERE ProcessBreakdown = 1 AND C.AccessorialFlg = 1
7754 GROUP BY C.RecordID, C.[Description], C.FinancialType
7755 END
7756END
7757-- ========================================================================================================
7758 -- CHARGES END
7759 -- ========================================================================================================
7760
7761 -- reverse logistics
7762 IF @ProcessRLOrderParty = 1
7763 BEGIN
7764 INSERT INTO #RLOrderParty
7765 (
7766 RLOrderParty_RecordID,
7767 RLCarrierName,
7768 RLOperatingCompany
7769 )
7770 SELECT
7771 RecordID,
7772 P.[RL Carrier],
7773 P.[RLOP Company]
7774 FROM
7775 (
7776 SELECT
7777 R.RecordID,
7778 OP.Role,
7779 OP.Name
7780 FROM #Row AS R
7781 INNER JOIN dbo.COServiceParty AS CSP WITH (NOLOCK)
7782 ON R.TicketServiceID = CSP.COServiceID
7783 INNER JOIN dbo.OrderParty AS OP WITH (NOLOCK)
7784 ON CSP.OrderPartyID = OP.OrderPartyID
7785 ) AS UP
7786 PIVOT
7787 (
7788 MAX(UP.Name) FOR UP.Role IN ([RL Carrier], [RLOP Company])
7789 ) AS P
7790 END
7791
7792 IF @ProcessRLSCAC = 1
7793 BEGIN
7794 INSERT INTO #RLSCAC
7795 (
7796 RLSCAC_RecordID,
7797 RLSCAC
7798 )
7799 SELECT
7800 R.RecordID,
7801 OP.SCAC
7802 FROM #Row AS R
7803 INNER JOIN dbo.COServiceParty AS CSP WITH (NOLOCK)
7804 ON R.TicketServiceID = CSP.COServiceID
7805 INNER JOIN dbo.OrderParty AS OP WITH (NOLOCK)
7806 ON CSP.OrderPartyID = OP.OrderPartyID
7807 WHERE OP.Role = 'RL Carrier'
7808 END
7809
7810 IF @ProcessRLTicket = 1
7811 BEGIN
7812 INSERT INTO #RLTicket
7813 (
7814 RLTicket_RecordID,
7815 RLTicketNumber,
7816 RLStatus,
7817 RLSealSigned,
7818 RLSealNumber,
7819 RLSealIntact,
7820 RLTotalBOLPieces,
7821 RLTotalBOLPiecesSigned,
7822 RLReturnMiles,
7823 RLCustomerPickup
7824 )
7825 SELECT
7826 R.RecordID,
7827 T.TicketNumber,
7828 T.TicketStatus,
7829 ISNULL(T.SealSignedFlg, 0),
7830 T.SealNumber,
7831 T.SealIntactFlg,
7832 T.TotalBOLQuantity,
7833 T.TotalQuantitySigned,
7834 T.ReturnDistance,
7835 ISNULL(T.CustomerPickUpFlg, 0)
7836 FROM #Row AS R
7837 INNER JOIN dbo.RLTicket AS T WITH (NOLOCK)
7838 ON R.TicketServiceID = T.COServiceID
7839 END
7840
7841 IF @ProcessRLTicketDate = 1
7842 BEGIN
7843 --spitkyl: changed because we are now pulling dates AND times
7844 --got this from how trans report date/time data is collected
7845 CREATE TABLE #RLDateTimeMapping
7846 (
7847 NameInColumnTable VARCHAR(50),
7848 NameInSourceTable VARCHAR(50)
7849 )
7850
7851 INSERT INTO [#RLDateTimeMapping] (NameInColumnTable,NameInSourceTable)
7852 SELECT 'RLTicketCreateDate', 'Create Date' UNION ALL
7853 SELECT 'RLTicketCreateTime', 'Create Time' UNION ALL
7854 SELECT 'RLTicketInitialShipDate', 'Headhaul Pickup Date' UNION ALL
7855 SELECT 'RLTicketInitialDeliveryDate', 'Headhaul Delivery Date' UNION ALL
7856 SELECT 'RLTicketStatusUpdateDate', 'Ticket Status Date' UNION ALL
7857 SELECT 'RLTicketStatusUpdateTime', 'Ticket Status Time'
7858
7859 CREATE TABLE #UnpivotedRLDates
7860 (
7861 RLTicketID INT,
7862 DateTimeType VARCHAR(100),
7863 DateTimeValue INT
7864 )
7865
7866 INSERT INTO [#UnpivotedRLDates] (RLTicketID,DateTimeType,DateTimeValue)
7867 SELECT
7868 UP.RLTicketID,
7869 CASE UP.SourceDateTimeColumn
7870 WHEN 'TimeValue' THEN REPLACE(UP.DateType,'Date','Time')
7871 ELSE UP.DateType END,
7872 UP.TheDateTimeType
7873
7874 FROM
7875 (
7876 SELECT T.RLTicketID, RLD.DateType, RLD.DateValue, RLD.TimeValue
7877 FROM #Row AS R
7878 INNER JOIN dbo.RLTicket AS T WITH (NOLOCK)
7879 ON R.TicketServiceID = T.COServiceID
7880 INNER JOIN dbo.RLTicketDate AS RLD WITH (NOLOCK)
7881 ON T.RLTicketID = RLD.RLTicketID
7882 WHERE EXISTS (SELECT 1 FROM [#RLDateTimeMapping] AS RLDM
7883 INNER JOIN #Column AS C
7884 ON RLDM.NameInColumnTable = C.CName
7885 WHERE RLD.DateType = RLDM.NameInSourceTable)
7886 ) as p
7887
7888 UNPIVOT
7889 (
7890 TheDateTimeType FOR SourceDateTimeColumn IN
7891 (
7892 p.DateValue,
7893 p.TimeValue
7894 )
7895 ) AS up
7896
7897 OPTION(LOOP JOIN)
7898
7899 DROP TABLE #RLDateTimeMapping
7900
7901 INSERT INTO #RLTicketDate
7902 (
7903 RLTicketDate_RecordID,
7904 RLTicketCreateDate,
7905 RLTicketCreateTime,
7906 RLTicketInitialShipDate,
7907 RLTicketInitialDeliveryDate,
7908 RLTicketStatusUpdateDate,
7909 RLTicketStatusUpdateTime
7910 )
7911 SELECT
7912 RecordID,
7913 P.[Create Date],
7914 P.[Create Time],
7915 P.[Headhaul Pickup Date],
7916 P.[Headhaul Delivery Date],
7917 P.[Ticket Status Date],
7918 P.[Ticket Status Time]
7919 FROM
7920 (
7921 SELECT R.RecordID, URLD.DateTimeType, MIN(URLD.DateTimeValue) AS DateTimeValue
7922 FROM #Row AS R
7923 INNER JOIN dbo.RLTicket AS T WITH (NOLOCK)
7924 ON R.TicketServiceID = T.COServiceID
7925INNER JOIN [#UnpivotedRLDates] AS URLD
7926 ON T.RLTicketID = URLD.RLTicketID
7927 GROUP BY R.RecordID, URLD.DateTimeType
7928 ) AS UP
7929 PIVOT
7930 (
7931 MIN(UP.DateTimeValue) FOR UP.DateTimeType IN
7932 (
7933 [Create Date],
7934 [Create Time],
7935 [Headhaul Pickup Date],
7936 [Headhaul Delivery Date],
7937 [Ticket Status Date],
7938 [Ticket Status Time]
7939 )
7940 ) AS P
7941 END
7942
7943 IF @ProcessRLLocation = 1
7944 BEGIN
7945 INSERT INTO #RLLocation
7946 (
7947 RLLocation_RecordID,
7948 RLHeadHaulOrigName,
7949 RLHeadHaulOrigAddress,
7950 RLHeadHaulOrigCity,
7951 RLHeadHaulOrigState,
7952 RLHeadHaulOrigZip,
7953 RLHeadHaulOrigOE,
7954
7955 RLHeadHaulDestName,
7956 RLHeadHaulDestAddress,
7957 RLHeadHaulDestCity,
7958 RLHeadHaulDestState,
7959 RLHeadHaulDestZip,
7960 RLHeadHaulDestOE,
7961
7962 RLReturnOrigName,
7963 RLReturnOrigAddress,
7964 RLReturnOrigCity,
7965 RLReturnOrigState,
7966 RLReturnOrigZip,
7967 RLReturnOrigOE,
7968
7969 RLReturnDestName,
7970 RLReturnDestAddress,
7971 RLReturnDestCity,
7972 RLReturnDestState,
7973 RLReturnDestZip,
7974 RLReturnDestOE
7975 )
7976 SELECT
7977 RecordID,
7978 HeadHaulOrig.Name,
7979 HeadHaulOrig.Address1,
7980 HeadHaulOrig.City,
7981 HeadHaulOrig.State,
7982 HeadHaulOrig.PostalCode,
7983 HHO.LocationPartyNumber,
7984
7985 HeadHaulDest.Name,
7986 HeadHaulDest.Address1,
7987 HeadHaulDest.City,
7988 HeadHaulDest.State,
7989 HeadHaulDest.PostalCode,
7990 HHD.LocationPartyNumber,
7991
7992 ReturnOrig.Name,
7993 ReturnOrig.Address1,
7994 ReturnOrig.City,
7995 ReturnOrig.State,
7996 ReturnOrig.PostalCode,
7997 RTO.LocationPartyNumber,
7998
7999 ReturnDest.Name,
8000 ReturnDest.Address1,
8001 ReturnDest.City,
8002 ReturnDest.State,
8003 ReturnDest.PostalCode,
8004 RTD.LocationPartyNumber
8005 FROM #Row AS R
8006 INNER JOIN dbo.COSDetail AS COSD WITH (NOLOCK)
8007 ON R.TicketServiceID = COSD.COServiceID
8008 LEFT OUTER JOIN dbo.COLocation AS HHO WITH (NOLOCK)
8009 ON COSD.COSDetailID = HHO.COSDetailID
8010 AND HHO.COLocationType = 'HH'
8011 AND HHO.LocationType = 'P'
8012 LEFT OUTER JOIN NTSR.dbo.DimLocation AS HeadHaulOrig WITH (NOLOCK)
8013 ON HHO.KeyLocationID = HeadHaulOrig.KeyLocationID
8014 LEFT OUTER JOIN dbo.COLocation AS HHD WITH (NOLOCK)
8015 ON COSD.COSDetailID = HHD.COSDetailID
8016 AND HHD.COLocationType = 'HH'
8017 AND HHD.LocationType = 'D'
8018 LEFT OUTER JOIN NTSR.dbo.DimLocation AS HeadHaulDest WITH (NOLOCK)
8019 ON HHD.KeyLocationID = HeadHaulDest.KeyLocationID
8020 LEFT OUTER JOIN dbo.COLocation AS RTO WITH (NOLOCK)
8021 ON COSD.COSDetailID = RTO.COSDetailID
8022 AND RTO.COLocationType = 'RT'
8023 AND RTO.LocationType = 'P'
8024 LEFT OUTER JOIN NTSR.dbo.DimLocation AS ReturnOrig WITH (NOLOCK)
8025 ON RTO.KeyLocationID = ReturnOrig.KeyLocationID
8026 LEFT OUTER JOIN dbo.COLocation AS RTD WITH (NOLOCK)
8027 ON COSD.COSDetailID = RTD.COSDetailID
8028 AND RTD.COLocationType = 'RT'
8029 AND RTD.LocationType = 'D'
8030 LEFT OUTER JOIN NTSR.dbo.DimLocation AS ReturnDest WITH (NOLOCK)
8031 ON RTD.KeyLocationID = ReturnDest.KeyLocationID
8032 END
8033
8034 IF @ProcessRLReference = 1
8035 BEGIN
8036 CREATE TABLE #TempRefs
8037 (
8038 RecordID INT,
8039 RefNumber NVARCHAR(255),
8040 RefType VARCHAR(50)
8041 )
8042
8043 INSERT INTO #TempRefs
8044 (
8045 RecordID,
8046 RefNumber,
8047 RefType
8048 )
8049 SELECT
8050 R.RecordID,
8051 Ref.ReferenceNumber,
8052 CSR.ReferenceType
8053 FROM #Row AS R
8054 INNER JOIN dbo.COServiceReference AS CSR WITH (NOLOCK)
8055 ON R.TicketServiceID = CSR.COServiceID
8056 INNER JOIN NTSR.dbo.DimReference AS Ref WITH (NOLOCK)
8057 ON Ref.KeyReferenceID = CSR.KeyReferenceID
8058 UNION ALL
8059 SELECT
8060 R.RecordID,
8061 Ref.ReferenceNumber,
8062 COSDR.ReferenceType
8063 FROM #Row AS R
8064 INNER JOIN dbo.COSDetail AS COSD WITH (NOLOCK)
8065 ON R.TicketServiceID = COSD.COServiceID
8066 INNER JOIN dbo.COSDetailReference AS COSDR WITH (NOLOCK)
8067 ON COSD.COSDetailID = COSDR.COSDetailID
8068 INNER JOIN NTSR.dbo.DimReference AS Ref WITH (NOLOCK)
8069 ON Ref.KeyReferenceID = COSDR.KeyReferenceID
8070
8071 INSERT INTO #RLReference
8072 (
8073 RLReference_RecordID,
8074 RLProNumber,
8075 RLSBOLNum,
8076 RLCustomerPO,
8077 RLCustomerOrderNum,
8078 RLRANum,
8079 RLCustRefNum,
8080 RLPickupNumber
8081 )
8082 SELECT
8083 RecordID,
8084 P.[HH RL Pro Number],
8085 P.[SBOL],
8086 P.[Cust PO],
8087 P.[RL Customer Order Number],
8088 P.[Return Authorization Number],
8089 P.[Customer Specific Reference Number],
8090 P.[Pickup Number]
8091 FROM
8092 (
8093 SELECT RecordID, RefNumber, RefType
8094 FROM #TempRefs
8095 ) AS UP
8096 PIVOT
8097 (
8098 MAX(UP.RefNumber) FOR RefType IN
8099 (
8100 [HH RL Pro Number],
8101 [SBOL],
8102 [Cust PO],
8103 [RL Customer Order Number],
8104 [Return Authorization Number],
8105 [Customer Specific Reference Number],
8106 [Pickup Number]
8107 )
8108 ) AS P
8109 END
8110
8111 IF @ProcessRLItem = 1
8112 BEGIN
8113 INSERT INTO #RLItem
8114 (
8115 RLItem_RecordID,
8116 RLProductName,
8117 RLItemValue,
8118 RLItemQuantity,
8119 RLItemWeight,
8120 RLSKU,
8121 RLDamaged,
8122 RLAccepted,
8123 RLSalvageable,
8124 RLDisposition,
8125 RLReason,
8126 RLEventType,
8127 RLErrorCode,
8128 RLProductOperatingCompany,
8129 COItemID
8130 )
8131 SELECT
8132 R.RecordID,
8133 I.Commodity,
8134 I.Value,
8135 I.ActualQuantity,
8136 RI.LineWeight,
8137 I.SKU,
8138 ISNULL(RI.DamagedFlg, 0),
8139 ISNULL(RI.AcceptedFlg, 0),
8140 ISNULL(RI.SalvageableFlg, 0),
8141 RI.Disposition,
8142RI.Reason,
8143 RI.EventType,
8144 RI.ErrorType,
8145 RI.ItemOCompany,
8146 RI.COItemID
8147 FROM #Row AS R
8148 INNER JOIN dbo.COSDetail AS COSD WITH (NOLOCK)
8149 ON R.TicketServiceID = COSD.COServiceID
8150 INNER JOIN dbo.COItem AS I WITH (NOLOCK)
8151 ON COSD.COSDetailID = I.COSDetailID
8152 INNER JOIN dbo.RLItem AS RI WITH (NOLOCK)
8153 ON I.COItemID = RI.COItemID
8154
8155 IF EXISTS (SELECT 1 FROM #Column AS C WHERE C.CName = 'RLShortCode')
8156 BEGIN
8157 UPDATE RI SET
8158 RLShortCode = R.ReferenceNumber
8159 FROM #RLItem AS RI
8160 INNER JOIN dbo.COItemReference AS IR WITH (NOLOCK)
8161 ON RI.COItemID = IR.COItemID
8162 AND IR.ReferenceType = 'Product Code'
8163 INNER JOIN NTSR.dbo.DimReference AS R WITH (NOLOCK)
8164 ON IR.KeyReferenceID = R.KeyReferenceID
8165 END
8166
8167 IF EXISTS (SELECT 1 FROM #Column AS C WITH (NOLOCK) WHERE C.CName = 'RLComments')
8168 BEGIN
8169 UPDATE RI SET
8170 RLComments = N.Note
8171 FROM #RLItem AS RI
8172 INNER JOIN dbo.COItemNote AS N WITH (NOLOCK)
8173 ON RI.COItemID = N.COItemID
8174 END
8175 END
8176
8177IF @ProcessRLSummaryItem = 1
8178 BEGIN
8179 INSERT INTO #RLSummaryItem
8180 (
8181 RLSummaryItem_RecordID,
8182 RLSummaryValue,
8183 RLSummaryQuantity
8184 )
8185 SELECT
8186 R.RecordID,
8187 SUM(ISNULL(I.Value, 0)),
8188 SUM(ISNULL(I.ActualQuantity, 0))
8189 FROM #Row AS R
8190 INNER JOIN dbo.COSDetail AS COSD WITH (NOLOCK)
8191 ON COSD.COServiceID = R.TicketServiceID
8192 INNER JOIN dbo.COItem AS I WITH (NOLOCK)
8193 ON COSD.COSDetailID = I.COSDetailID
8194 GROUP BY R.RecordID
8195 END
8196
8197 IF @ProcessDropTrailer = 1
8198 BEGIN
8199 INSERT INTO #DropTrailer
8200 (
8201 DropTrailer_RecordID,
8202 DropTrailerShipper,
8203 DropTrailerConsignee,
8204 DropTrailerNotifiedByShipper,
8205 DropTrailerNotifiedByConsignee,
8206 ReceivedBy,
8207 PiecesDelivered
8208 )
8209 -- could probably go through pdetail as well - did not notice that table until
8210 -- I had already written this 30 minutes before a go/no-go...
8211 SELECT DISTINCT
8212 RecordID,
8213 CONVERT(BIT, CustomerPick.DropTrailerFlag),
8214 CONVERT(BIT, CustomerDrop.DropTrailerFlag),
8215 CustomerPick.DropTrailerFlagNotifiedByFirstName + ' ' + CustomerPick.DropTrailerFlagNotifiedByLastName,
8216 CustomerDrop.DropTrailerFlagNotifiedByFirstName + ' ' + CustomerDrop.DropTrailerFlagNotifiedByLastName,
8217 DropLeg.POD, --SPODL_DROP.POD,
8218 DropLeg.PiecesDelivered
8219 FROM #Row AS R
8220 INNER JOIN dbo.SPODetail AS DropLeg WITH (NOLOCK)
8221 ON R.LoadNumber = DropLeg.LoadNumber
8222 AND R.SourceTypeID = DropLeg.SourceTypeID
8223 AND R.DestStopNumber = DropLeg.EndStopNumber
8224 INNER JOIN dbo.SPODetail AS PickLeg WITH (NOLOCK)
8225 ON R.LoadNumber = PickLeg.LoadNumber
8226 AND R.SourceTypeID = PickLeg.SourceTypeID
8227 AND R.OriginStopNumber = PickLeg.StartStopNumber
8228 INNER JOIN dbo.SPODLocation AS CustomerPick WITH (NOLOCK)
8229 ON PickLeg.SPODetailID = CustomerPick.SPODetailID
8230 AND PickLeg.StartStopNumber = CustomerPick.StopNumber
8231 AND CustomerPick.LocationType = 'P'
8232 INNER JOIN dbo.SPODLocation AS CustomerDrop WITH (NOLOCK)
8233 ON DropLeg.SPODetailID = CustomerDrop.SPODetailID
8234 AND DropLeg.EndStopNumber = CustomerDrop.StopNumber
8235 AND CustomerDrop.LocationType = 'D'
8236
8237
8238 UPDATE DT SET DeleteFlg = 1
8239 FROM #DropTrailer AS DT
8240 WHERE EXISTS (SELECT 1 FROM #DropTrailer AS DT2
8241 WHERE DT.DropTrailer_RecordID = DT2.DropTrailer_RecordID
8242 GROUP BY DT2.DropTrailer_RecordID
8243 HAVING COUNT(1) > 1)
8244
8245 INSERT INTO #DropTrailer
8246 (
8247 DropTrailer_RecordID,
8248 DropTrailerShipper,
8249 DropTrailerConsignee,
8250 DropTrailerNotifiedByShipper,
8251 DropTrailerNotifiedByConsignee,
8252 ReceivedBy,
8253 PiecesDelivered
8254 )
8255 SELECT DISTINCT
8256 DT.DropTrailer_RecordID,
8257 (
8258 SELECT MAX(CONVERT(INT, DT2.DropTrailerShipper))
8259 FROM #DropTrailer AS DT2
8260 WHERE DT2.DropTrailer_RecordID = DT.DropTrailer_RecordID
8261 GROUP BY DT2.DropTrailer_RecordID
8262 ) AS DropTrailerShipper,
8263 (
8264 SELECT MAX(CONVERT(INT, DT2.DropTrailerConsignee))
8265FROM #DropTrailer AS DT2
8266WHERE DT2.DropTrailer_RecordID = DT.DropTrailer_RecordID
8267 GROUP BY DT2.DropTrailer_RecordID
8268 ) AS DropTrailerConsignee,
8269 SUBSTRING((
8270 SELECT DT2.DropTrailerNotifiedByShipper + ', '
8271 FROM #DropTrailer AS DT2
8272 WHERE DT.DropTrailer_RecordID = DT2.DropTrailer_RecordID
8273 GROUP BY DropTrailerNotifiedByShipper
8274 FOR XML PATH('')
8275 ), 0, 199) AS DropTrailerNotifiedByShipper,
8276 SUBSTRING((
8277 SELECT DT2.DropTrailerNotifiedByConsignee + ', '
8278 FROM #DropTrailer AS DT2
8279 WHERE DT.DropTrailer_RecordID = DT2.DropTrailer_RecordID
8280 GROUP BY DropTrailerNotifiedByConsignee
8281 FOR XML PATH('')
8282 ), 0, 199) AS DropTrailerNotifiedByConsignee,
8283 SUBSTRING((
8284 SELECT DT2.ReceivedBy + '; '
8285 FROM #DropTrailer AS DT2
8286 WHERE DT.DropTrailer_RecordID = DT2.DropTrailer_RecordID
8287 GROUP BY DT2.ReceivedBy
8288 FOR XML PATH('')
8289 ), 0, 199) AS ReceivedBy,
8290 SUBSTRING((
8291 SELECT DT2.PiecesDelivered + ', '
8292 FROM #DropTrailer AS DT2
8293 WHERE DT.DropTrailer_RecordID = DT2.DropTrailer_RecordID
8294 GROUP BY DT2.PiecesDelivered
8295 FOR XML PATH('')
8296 ), 0, 199) AS PiecesDelivered
8297 FROM #DropTrailer AS DT
8298 WHERE DeleteFlg = 1
8299
8300 DELETE FROM #DropTrailer WHERE DeleteFlg = 1
8301 END
8302
8303 IF @ProcessINCOTerm = 1
8304 BEGIN
8305 INSERT INTO #INCOTerm
8306 (
8307INCOTerm_RecordID,
8308 INCOTerm,
8309INCOTermLocation
8310 )
8311 SELECT DISTINCT
8312 R.RecordID,
8313 CG.IncoTerms,
8314 CG.IncoTermsNamedLocation
8315 FROM #Row AS R
8316 INNER JOIN dbo.COSGroup AS CG WITH (NOLOCK)
8317 ON CG.COSGroupID = R.COSGroupID
8318 END
8319
8320 IF @ProcessReasonCodes = 1
8321 BEGIN
8322 CREATE TABLE #AlertCodes
8323 (
8324 Code VARCHAR(10)
8325 )
8326 INSERT INTO #AlertCodes(Code)
8327 SELECT 'DLATE' UNION ALL
8328 SELECT 'PLATE'
8329
8330 CREATE TABLE #TempReasonCodes
8331 (
8332 RecordID INT,
8333 AlertCode VARCHAR(10),
8334 ReasonDescription VARCHAR(255)
8335 )
8336
8337 INSERT INTO #TempReasonCodes
8338 (
8339 RecordID,
8340 AlertCode,
8341 ReasonDescription
8342 )
8343 SELECT
8344 R.RecordID,
8345 A.Code,
8346 A.ReasonDescription
8347 FROM #Row AS R
8348 INNER JOIN dbo.COSAlert AS CSA WITH (NOLOCK)
8349 ON R.COServiceID = CSA.COServiceID
8350 INNER JOIN dbo.Alert AS A WITH (NOLOCK)
8351 ON A.AlertID = CSA.AlertID
8352 INNER JOIN #AlertCodes AS AC
8353 ON A.Code = AC.Code
8354
8355 INSERT INTO #ReasonCodes
8356 (
8357 ReasonCodes_RecordID,
8358 PLATEReason,
8359 DLATEReason
8360 )
8361 SELECT
8362 RecordID,
8363 P.PLATE,
8364 P.DLATE
8365 FROM
8366 (
8367 SELECT RecordID, AlertCode, ReasonDescription
8368 FROM #TempReasonCodes
8369 WHERE NULLIF(ReasonDescription, '') IS NOT NULL
8370 ) AS TC
8371 PIVOT
8372 (
8373 MAX(TC.ReasonDescription) FOR AlertCode IN
8374 (
8375 PLATE,
8376 DLATE
8377 )
8378 ) AS P
8379 END
8380
8381 IF @ProcessEPayments = 1
8382 BEGIN
8383 -- could potentially split out this into
8384 -- each individual chrwonline table join...
8385 CREATE TABLE #OrderInvoices
8386 (
8387 RecordID INT,
8388 InvoiceNumber BIGINT,
8389 InvoiceID INT
8390 )
8391
8392 INSERT INTO #OrderInvoices
8393 (
8394 RecordID,
8395 InvoiceNumber,
8396 InvoiceID
8397 )
8398 SELECT DISTINCT
8399 R.RecordID,
8400 OI.InvoiceNumber,
8401 OI.InvoiceID
8402 FROM #Row AS R
8403 INNER JOIN dbo.COServiceInvoice AS CSI WITH (NOLOCK)
8404 ON R.COServiceID = CSI.COServiceID
8405 INNER JOIN dbo.OrderInvoice AS OI WITH (NOLOCK)
8406 ON OI.OrderInvoiceID = CSI.OrderInvoiceID
8407
8408 CREATE TABLE #EPayApprovedBy
8409 (
8410 RecordID INT,
8411 ApprovedBy VARCHAR(100),
8412 DeleteFlg BIT
8413 )
8414
8415 CREATE TABLE #EPayPaidBy
8416 (
8417 RecordID INT,
8418 PaidBy VARCHAR(100),
8419 DeleteFlg BIT
8420 )
8421
8422 CREATE TABLE #EPayComments
8423 (
8424 RecordID INT,
8425 Comments VARCHAR(255),
8426 DeleteFlg BIT
8427 )
8428
8429 INSERT INTO #EPayApprovedBy
8430 (
8431 RecordID,
8432 ApprovedBy
8433 )
8434 SELECT
8435 OI.RecordID,
8436 UR.FirstName + ' ' + UR.LastName
8437 FROM #OrderInvoices AS OI
8438 INNER JOIN CHRWOnline.dbo.UT_EPApprovedInvoice AS EPA WITH (NOLOCK)
8439 ON OI.InvoiceID = EPA.InvoiceID
8440 INNER JOIN CHRWOnline.dbo.UT_User AS U WITH (NOLOCK)
8441 ON U.UserID = EPA.UserID
8442 INNER JOIN CHRWOnline.dbo.UT_UserRequest AS UR WITH (NOLOCK)
8443 ON U.UserRequestID = UR.UserRequestID
8444 WHERE EPA.InvoiceType = 0 AND EPA.ApproveFlag = 1
8445 UNION
8446 SELECT
8447 OI.RecordID,
8448 UR.FirstName + ' ' + UR.LastName
8449 FROM #OrderInvoices AS OI
8450 INNER JOIN CHRWOnline.dbo.UT_EPApprovedInvoice AS EPA WITH (NOLOCK)
8451 ON OI.InvoiceNumber = EPA.InvoiceID
8452 INNER JOIN CHRWOnline.dbo.UT_User AS U WITH (NOLOCK)
8453 ON U.UserID = EPA.UserID
8454 INNER JOIN CHRWOnline.dbo.UT_UserRequest AS UR WITH (NOLOCK)
8455 ON U.UserRequestID = UR.UserRequestID
8456 WHERE EPA.InvoiceType = 1 AND EPA.ApproveFlag = 1
8457
8458 INSERT INTO #EPayPaidBy
8459 (
8460 RecordID,
8461 PaidBy
8462 )
8463 SELECT
8464 OI.RecordID,
8465 UR.FirstName + ' ' + UR.LastName
8466 FROM #OrderInvoices AS OI
8467 INNER JOIN CHRWOnline.dbo.UT_EPayTransaction AS EPT WITH (NOLOCK)
8468 ON OI.InvoiceID = EPT.InvoiceID
8469 AND EPT.InvoiceType = 0
8470 INNER JOIN CHRWOnline.dbo.UT_User AS U WITH (NOLOCK)
8471 ON U.UserID = EPT.UserID
8472 INNER JOIN CHRWOnline.dbo.UT_UserRequest AS UR WITH (NOLOCK)
8473 ON U.UserRequestID = UR.UserRequestID
8474 UNION
8475 SELECT
8476 OI.RecordID,
8477 UR.FirstName + ' ' + UR.LastName
8478 FROM #OrderInvoices AS OI
8479 INNER JOIN CHRWOnline.dbo.UT_EPayTransaction AS EPT WITH (NOLOCK)
8480 ON OI.InvoiceNumber = EPT.InvoiceID
8481 AND EPT.InvoiceType = 1
8482 INNER JOIN CHRWOnline.dbo.UT_User AS U WITH (NOLOCK)
8483 ON U.UserID = EPT.UserID
8484 INNER JOIN CHRWOnline.dbo.UT_UserRequest AS UR WITH (NOLOCK)
8485 ON U.UserRequestID = UR.UserRequestID
8486
8487 INSERT INTO #EPayComments
8488 (
8489 RecordID,
8490 Comments
8491 )
8492 SELECT
8493 OI.RecordID,
8494 EC.Comment
8495 FROM #OrderInvoices AS OI
8496 INNER JOIN CHRWOnline.dbo.UT_EPComments AS EC WITH (NOLOCK)
8497 ON OI.InvoiceID = EC.InvoiceID
8498 UNION
8499 SELECT
8500 OI.RecordID,
8501 EC.Comment
8502 FROM #OrderInvoices AS OI
8503 INNER JOIN CHRWOnline.dbo.UT_EPComments AS EC WITH (NOLOCK)
8504 ON OI.InvoiceNumber = EC.InvoiceID
8505
8506 UPDATE EPA SET DeleteFlg = 1
8507 FROM #EPayApprovedBy AS EPA
8508 WHERE EXISTS
8509 (
8510 SELECT 1 FROM #EPayApprovedBy AS EPA2
8511 WHERE EPA2.RecordID = EPA.RecordID
8512 GROUP BY EPA2.RecordID
8513 HAVING COUNT(1) > 1
8514 )
8515
8516 UPDATE EPP SET DeleteFlg = 1
8517 FROM #EPayPaidBy AS EPP
8518 WHERE EXISTS
8519 (
8520 SELECT 1 FROM #EPayPaidBy AS EPP2
8521 WHERE EPP2.RecordID = EPP.RecordID
8522 GROUP BY EPP2.RecordID
8523 HAVING COUNT(1) > 1
8524 )
8525
8526 UPDATE EPC SET DeleteFlg = 1
8527 FROM #EPayComments AS EPC
8528 WHERE EXISTS
8529 (
8530 SELECT 1 FROM #EPayComments AS EPC2 WITH (NOLOCK)
8531 WHERE EPC2.RecordID = EPC.RecordID
8532 GROUP BY EPC2.RecordID
8533 HAVING COUNT(1) > 1
8534 )
8535
8536 INSERT INTO #EPayApprovedBy
8537 (
8538 RecordID,
8539 ApprovedBy
8540 )
8541 SELECT
8542 EPA.RecordID,
8543 (
8544 SELECT ApprovedBy + ', '
8545 FROM #EPayApprovedBy AS EPA2
8546 WHERE EPA2.RecordID = EPA.RecordID
8547 FOR XML PATH('')
8548 ) AS ApprovedBy
8549 FROM #EPayApprovedBy AS EPA
8550 WHERE DeleteFlg = 1
8551
8552 INSERT INTO #EPayPaidBy
8553 (
8554 RecordID,
8555 PaidBy
8556 )
8557 SELECT
8558 EPP.RecordID,
8559 (
8560 SELECT PaidBy + ', '
8561 FROM #EPayPaidBy AS EPP2
8562 WHERE EPP2.RecordID = EPP.RecordID
8563 FOR XML PATH('')
8564 ) AS PaidBy
8565 FROM #EPayPaidBy AS EPP
8566 WHERE DeleteFlg = 1
8567
8568 INSERT INTO #EPayComments
8569 (
8570 RecordID,
8571 Comments
8572 )
8573 SELECT
8574 EC.RecordID,
8575 (
8576 SELECT Comments + ', '
8577 FROM #EPayComments AS EC2
8578 WHERE EC2.RecordID = EC.RecordID
8579 FOR XML PATH('')
8580 ) AS Comments
8581 FROM #EPayComments AS EC
8582 WHERE DeleteFlg = 1
8583
8584 DELETE FROM #EPayApprovedBy WHERE DeleteFlg = 1
8585 DELETE FROM #EPayPaidBy WHERE DeleteFlg = 1
8586 DELETE FROM #EPayComments WHERE DeleteFlg = 1
8587
8588 INSERT INTO #Epayments
8589 (
8590 EPayments_RecordID,
8591 EPayApprovedBy,
8592 EPayPaidBy,
8593 EPayComments
8594 )
8595 SELECT
8596R.RecordID,
8597 EPA.ApprovedBy,
8598 EPP.PaidBy,
8599 EC.Comments
8600 FROM #Row AS R
8601 LEFT OUTER JOIN #EPayApprovedBy AS EPA
8602 ON R.RecordID = EPA.RecordID
8603 LEFT OUTER JOIN #EPayPaidBy AS EPP
8604 ON R.RecordID = EPP.RecordID
8605LEFT OUTER JOIN #EPayComments AS EC
8606 ON R.RecordID = EC.RecordID
8607 END
8608
8609
8610 --PurchaseOrder related stuff
8611
8612 IF @ProcessPOItems = 1
8613 BEGIN
8614
8615
8616 INSERT INTO #POItems
8617 (
8618 POItems_RecordID
8619 ,InnerPackOriginalQuantity ,InnerPackQuantity ,InnerPackWeight
8620 ,InnerPackType ,InnerPackLength ,InnerPackWidth ,InnerPackHeight
8621 ,InnerPackVolume ,OuterPackStuffingQuantity ,OuterPackType ,OuterPackLength
8622 ,OuterPackWidth ,OuterPackHeight ,OuterPackVolume ,OuterPackWeight
8623 ,OuterPackQuantity ,POSKU ,POProductCode ,POHTCode ,ItemName
8624 ,TotalValue ,POMode ,POItemStatus
8625 ,POINCOTerm,INCOLocation,POStatus,COItemID,POItemID,PlannedQuantity,InTransitQuantity,DeliveredQuantity
8626 )
8627 SELECT
8628 R.RecordID
8629 ,Item.InnerPackOriginalQuantity,Item.InnerPackUpdatedQuantity_OrderedQuantity,Item.InnerPackWeight
8630 ,Item.InnerPackType,Item.InnerPackLength,Item.InnerPackWidth,Item.InnerPackHeight
8631 ,Item.InnerPackVolume,Item.OuterPackStuffingQuantity,Item.OuterPackType,Item.OuterPackLength
8632 ,Item.OuterPackWidth,Item.OuterPackHeight,Item.OuterPackVolume,Item.OuterPackWeight
8633 ,Item.OuterPackQuantity,Item.SKU,Item.ProductCode,Item.HTCode,Item.ProductName
8634 ,Item.InnerPackTotalValue,
8635 CASE
8636 WHEN Item.RequestedMode = 'S' THEN 'Ocean'
8637 WHEN Item.RequestedMode = 'A' THEN 'Air'
8638 END AS RequestedMode,Item.POItemStatus
8639 ,PO.INCOTerms,PO.INCOLocation,PO.POStatus,COI.COItemID,Item.POItemID,item.PlannedQuantity,Item.InTransitQuantity,Item.DeliveredQuantity
8640 FROM #Row AS R
8641 INNER JOIN dbo.POItem AS Item WITH (NOLOCK) ON Item.POItemID = R.POItemID
8642 INNER JOIN dbo.COItem AS COI WITH (NOLOCK) ON COI.COItemID = R.COItemID
8643 INNER JOIN dbo.POrder AS PO WITH (NOLOCK) ON Item.POrderID = PO.POrderID
8644 IF @ProcessItems = 1
8645 BEGIN
8646 DELETE FROM I
8647 FROM #Item AS I
8648 LEFT JOIN #POItems P ON I.ItemID = P.COItemID AND I.Item_RecordID = P.POItems_RecordID
8649 WHERE P.COItemID IS NULL
8650 END
8651
8652 END
8653
8654
8655 IF @ProcessPOCustomer = 1
8656 BEGIN
8657 INSERT INTO #POCustomer
8658 (
8659 POCustomer_RecordID
8660 ,POCustomerName
8661 ,CustomerAccountCode
8662 ,PartyNumber
8663 )
8664 SELECT
8665 R.RecordID
8666 ,OP.Name
8667 ,OP.PartyCode
8668 ,OP.PartyNumber
8669 FROM #Row AS R
8670 INNER JOIN dbo.POrderParty AS POP WITH (NOLOCK) ON R.POID = POP.POrderID
8671 INNER JOIN dbo.OrderParty AS OP WITH (NOLOCK) ON POP.OrderPartyID = OP.OrderPartyID AND OP.[Role] = 'CUSTOMER'
8672
8673 UPDATE
8674 PC
8675 SET
8676 PC.CustomerAddress1 = PA.[Address1],
8677 PC.CustomerAddress2 = PA.[Address2],
8678 PC.CustomerCity = PA.[City],
8679 PC.CustomerState = PA.[State],
8680 PC.CustomerPostalCode = PA.[PostalCode]
8681 FROM
8682 #POCustomer AS PC
8683 INNER JOIN
8684 MDMPublicReadOnly.mdm.Party AS P WITH(NOLOCK)
8685 ON PC.PartyNumber = P.PartyNumber
8686 INNER JOIN
8687 MDMPublicReadOnly.mdm.PartyAddress AS PA WITH(NOLOCK)
8688 ON PC.PartyNumber = PA.PartyNumber
8689 AND PA.PartyAddressTypeID = 2 -- Company address
8690 AND PA.Deleted = 0
8691
8692 END
8693
8694 IF @ProcessPOBuyer = 1
8695 BEGIN
8696 INSERT INTO #POBuyer
8697 (
8698 POBuyer_RecordID
8699 ,BuyerName
8700 ,BuyerAccountCode
8701 ,PartyNumber
8702 )
8703 SELECT
8704 R.RecordID
8705 ,OP.Name
8706 ,OP.PartyCode
8707 ,OP.PartyNumber
8708 FROM #Row AS R
8709 INNER JOIN dbo.POrderParty AS POP WITH (NOLOCK) ON R.POID = POP.POrderID
8710 INNER JOIN dbo.OrderParty AS OP WITH (NOLOCK) ON POP.OrderPartyID = OP.OrderPartyID AND OP.[Role] = 'BUYER'
8711
8712 UPDATE
8713 PBY
8714 SET
8715 PBY.BuyerAddress1 = PA.[Address1],
8716 PBY.BuyerAddress2 = PA.[Address2],
8717 PBY.BuyerCity = PA.[City],
8718 PBY.BuyerState = PA.[State],
8719 PBY.BuyerPostalCode = PA.[PostalCode]
8720 FROM
8721 #POBuyer AS PBY
8722 INNER JOIN
8723 MDMPublicReadOnly.mdm.Party AS P WITH(NOLOCK)
8724 ON PBY.PartyNumber = P.PartyNumber
8725 INNER JOIN
8726 MDMPublicReadOnly.mdm.PartyAddress AS PA WITH(NOLOCK)
8727 ON PBY.PartyNumber = PA.PartyNumber
8728 AND PA.PartyAddressTypeID = 2 -- Company address
8729 AND PA.Deleted = 0
8730 END
8731
8732 IF @ProcessPOEndCustomer = 1
8733 BEGIN
8734 INSERT INTO #POEndCustomer
8735 (
8736 EndCustomer_RecordID
8737 ,EndCustomerName
8738 ,EndCustomerAccountCode
8739 ,PartyNumber
8740 )
8741 SELECT
8742 R.RecordID
8743 ,OP.Name
8744 ,OP.PartyCode
8745 ,OP.PartyNumber
8746 FROM #Row AS R
8747 INNER JOIN dbo.POrderParty AS POP WITH (NOLOCK) ON R.POID = POP.POrderID
8748 INNER JOIN dbo.OrderParty AS OP WITH (NOLOCK) ON POP.OrderPartyID = OP.OrderPartyID AND OP.[Role] = 'End Customer'
8749
8750 UPDATE
8751 ECUS
8752 SET
8753 ECUS.EndCustomerAddress1 = PA.[Address1],
8754 ECUS.EndCustomerAddress2 = PA.[Address2],
8755 ECUS.EndCustomerCity = PA.[City],
8756 ECUS.EndCustomerState = PA.[State],
8757 ECUS.EndCustomerPostalCode = PA.[PostalCode]
8758 FROM
8759 #POEndCustomer AS ECUS
8760 INNER JOIN
8761 MDMPublicReadOnly.mdm.Party AS P WITH(NOLOCK)
8762 ON ECUS.PartyNumber = P.PartyNumber
8763 INNER JOIN
8764 MDMPublicReadOnly.mdm.PartyAddress AS PA WITH(NOLOCK)
8765 ON ECUS.PartyNumber = PA.PartyNumber
8766 AND PA.PartyAddressTypeID = 2 -- Company address
8767 AND PA.Deleted = 0
8768 END
8769
8770 IF @ProcessPOImporter = 1
8771 BEGIN
8772 INSERT INTO #POImporterofRecord
8773 (
8774 ImporterofRecord_RecordID
8775 ,ImporterofRecordName
8776 ,ImporterofRecordAccountCode
8777 ,PartyNumber
8778 )
8779 SELECT
8780 R.RecordID
8781 ,OP.Name
8782 ,OP.PartyCode
8783 ,OP.PartyNumber
8784 FROM #Row AS R
8785 INNER JOIN dbo.POrderParty AS POP WITH (NOLOCK) ON R.POID = POP.POrderID
8786 INNER JOIN dbo.OrderParty AS OP WITH (NOLOCK) ON POP.OrderPartyID = OP.OrderPartyID AND OP.[Role] = 'IMPORTEROFRECORD'
8787
8788 UPDATE
8789 IMP
8790 SET
8791 IMP.ImporterofRecordAddress1 = PA.[Address1],
8792 IMP.ImporterofRecordAddress2 = PA.[Address2],
8793 IMP.ImporterofRecordCity = PA.[City],
8794 IMP.ImporterofRecordState = PA.[State],
8795 IMP.ImporterofRecordPostalCode = PA.[PostalCode]
8796 FROM
8797 #POImporterofRecord AS IMP
8798 INNER JOIN
8799 MDMPublicReadOnly.mdm.Party AS P WITH(NOLOCK)
8800 ON IMP.PartyNumber = P.PartyNumber
8801 INNER JOIN
8802 MDMPublicReadOnly.mdm.PartyAddress AS PA WITH(NOLOCK)
8803 ON IMP.PartyNumber = PA.PartyNumber
8804 AND PA.PartyAddressTypeID = 2 -- Company address
8805 AND PA.Deleted = 0
8806 END
8807
8808 IF @ProcessPOVendor = 1
8809 BEGIN
8810 INSERT INTO #POVendor
8811 (
8812 POVendor_RecordID
8813 ,POVendorName
8814 ,VendorAccountCode
8815 ,PartyNumber
8816 )
8817 SELECT
8818 R.RecordID
8819 ,OP.Name
8820 ,OP.PartyCode
8821 ,OP.PartyNumber
8822 FROM #Row AS R
8823 INNER JOIN dbo.POItemParty AS POP WITH (NOLOCK) ON R.POItemID = POP.POItemID
8824 INNER JOIN dbo.OrderParty AS OP WITH (NOLOCK) ON POP.OrderPartyID = OP.OrderPartyID AND OP.[Role] = 'VENDOR'
8825
8826 UPDATE
8827 VEN
8828 SET
8829 VEN.VendorAddress1 = PA.[Address1],
8830 VEN.VendorAddress2 = PA.[Address2],
8831 VEN.VendorCity = PA.[City],
8832 VEN.VendorState = PA.[State],
8833 VEN.VendorPostalCode = PA.[PostalCode]
8834 FROM
8835 #POVendor AS VEN
8836 INNER JOIN
8837 MDMPublicReadOnly.mdm.Party AS P WITH(NOLOCK)
8838 ON VEN.PartyNumber = P.PartyNumber
8839 INNER JOIN
8840 MDMPublicReadOnly.mdm.PartyAddress AS PA WITH(NOLOCK)
8841 ON VEN.PartyNumber = PA.PartyNumber
8842 AND PA.PartyAddressTypeID = 2 -- Company address
8843 AND PA.Deleted = 0
8844 END
8845
8846 IF @ProcessPOManufacturer = 1
8847 BEGIN
8848 INSERT INTO #POManufacturer
8849 (
8850 Manufacturer_RecordID
8851 ,ManufacturerName
8852 ,ManufacturerAccountCode
8853 ,PartyNumber
8854 )
8855 SELECT
8856 R.RecordID
8857 ,OP.Name
8858 ,OP.PartyCode
8859 ,OP.PartyNumber
8860 FROM #Row AS R
8861 INNER JOIN dbo.POItemParty AS POP WITH (NOLOCK) ON R.POItemID = POP.POItemID
8862 INNER JOIN dbo.OrderParty AS OP WITH (NOLOCK) ON POP.OrderPartyID = OP.OrderPartyID AND OP.[Role] = 'Manufacturer'
8863
8864 UPDATE
8865 MAN
8866 SET
8867 MAN.ManufacturerAddress1 = PA.[Address1],
8868 MAN.ManufacturerAddress2 = PA.[Address2],
8869 MAN.ManufacturerCity = PA.[City],
8870 MAN.ManufacturerState = PA.[State],
8871 MAN.ManufacturerPostalCode = PA.[PostalCode]
8872 FROM
8873 #POManufacturer AS MAN
8874 INNER JOIN
8875 MDMPublicReadOnly.mdm.Party AS P WITH(NOLOCK)
8876 ON MAN.PartyNumber = P.PartyNumber
8877 INNER JOIN
8878 MDMPublicReadOnly.mdm.PartyAddress AS PA WITH(NOLOCK)
8879 ON MAN.PartyNumber = PA.PartyNumber
8880 AND PA.PartyAddressTypeID = 2 -- Company address
8881 AND PA.Deleted = 0
8882 END
8883
8884 IF @ProcessPOSeller = 1
8885 BEGIN
8886 INSERT INTO #POSeller
8887 (
8888 Seller_RecordID
8889 ,SellerName
8890 ,SellerAccountCode
8891 ,PartyNumber
8892 )
8893 SELECT
8894 R.RecordID
8895 ,OP.Name
8896 ,OP.PartyCode
8897 ,OP.PartyNumber
8898 FROM #Row AS R
8899 INNER JOIN dbo.POItemParty AS POP WITH (NOLOCK) ON R.POItemID = POP.POItemID
8900 INNER JOIN dbo.OrderParty AS OP WITH (NOLOCK) ON POP.OrderPartyID = OP.OrderPartyID AND OP.[Role] = 'SELLER'
8901
8902 UPDATE
8903 SELL
8904 SET
8905 SELL.SellerAddress1 = PA.[Address1],
8906 SELL.SellerAddress2 = PA.[Address2],
8907 SELL.SellerCity = PA.[City],
8908 SELL.SellerState = PA.[State],
8909 SELL.SellerPostalCode = PA.[PostalCode]
8910 FROM
8911 #POSeller AS SELL
8912 INNER JOIN
8913 MDMPublicReadOnly.mdm.Party AS P WITH(NOLOCK)
8914 ON SELL.PartyNumber = P.PartyNumber
8915 INNER JOIN
8916 MDMPublicReadOnly.mdm.PartyAddress AS PA WITH(NOLOCK)
8917 ON SELL.PartyNumber = PA.PartyNumber
8918 AND PA.PartyAddressTypeID = 2 -- Company address
8919 AND PA.Deleted = 0
8920 END
8921
8922 IF @ProcessPOLocation = 1
8923 BEGIN
8924 INSERT INTO #POItemLocation
8925 (
8926 POItemLocation_RecordID
8927 ,OriginLocationName
8928 ,OriginLocationCity
8929 ,OriginLocationState
8930 ,OriginLocationCountry
8931
8932 ,DestinationLocationName
8933 ,DestinationLocationCity
8934 ,DestinationLocationState
8935 ,DestinationLocationCountry
8936 )
8937 SELECT
8938 R.RecordID
8939 ,OL.Name
8940 ,OL.City
8941 ,OL.State
8942 ,OL.Country
8943 ,DL.Name
8944 ,DL.City
8945 ,DL.State
8946 ,DL.Country
8947 FROM #Row AS R
8948 LEFT OUTER JOIN dbo.POItemLocation AS OPOIL WITH (NOLOCK) ON R.POItemID = OPOIL.POItemID
8949 AND OPOIL.PartyRole ='Origin Location'
8950 LEFT OUTER JOIN NTSR.dbo.DimLocation AS OL WITH (NOLOCK) ON OL.KeyLocationID = OPOIL.KeyLocationID
8951
8952 LEFT OUTER JOIN dbo.POItemLocation AS DPOIL WITH (NOLOCK) ON R.POItemID = DPOIL.POItemID
8953 AND DPOIL.PartyRole ='Destination Location'
8954 LEFT OUTER JOIN NTSR.dbo.DimLocation AS DL WITH (NOLOCK) ON DL.KeyLocationID = DPOIL.KeyLocationID
8955 END
8956
8957 IF @ProcessPOItemDate =1
8958 BEGIN
8959
8960 CREATE TABLE #PODateTimeMapping
8961 (
8962 NameInColumnTable VARCHAR(50),
8963 NameInSourceTable VARCHAR(50)
8964 )
8965
8966 CREATE TABLE #UnpivotedPODates
8967 (
8968 POItemID INT,
8969 DateTimeType VARCHAR(100),
8970 DateTimeValue INT
8971 )
8972 INSERT INTO [#PODateTimeMapping] (NameInColumnTable,NameInSourceTable)
8973 SELECT 'RequestedBookingStartDate', 'RequestedBookingStartDate' UNION ALL
8974 SELECT 'RequestedBookingDate', 'RequestedBookingDate' UNION ALL
8975 SELECT 'ShipStartDate', 'ShipStartDate' UNION ALL
8976 SELECT 'ShipEndDate', 'ShipEndDate' UNION ALL
8977 SELECT 'RequestedPickupStartDate', 'RequestedPickupStartDate' UNION ALL
8978 SELECT 'RequestedPickupDate', 'RequestedPickUpDate' UNION ALL
8979 SELECT 'RequestedDeliveryStartDate', 'RequestedDeliveryStartDate' UNION ALL
8980 SELECT 'RequestedDeliveryDate', 'RequestedDeliveryDate'
8981
8982 INSERT INTO [#UnpivotedPODates] (POItemID,DateTimeType,DateTimeValue)
8983 SELECT
8984 UP.POItemID,
8985 CASE UP.SourceDateTimeColumn
8986 WHEN 'TimeValue' THEN REPLACE(UP.DateType,'Date','Time')
8987 ELSE UP.DateType END,
8988 UP.TheDateTimeType
8989
8990 FROM
8991 (
8992 SELECT P.POItemID, PID.DateType, PID.DateValue, PID.TimeValue
8993 FROM #Row AS R
8994 INNER JOIN dbo.POItem AS P WITH (NOLOCK)
8995 ON R.POItemID = P.POItemID
8996 INNER JOIN dbo.POItemDate AS PID WITH (NOLOCK)
8997 ON P.POItemID = PID.POItemID
8998 WHERE EXISTS (SELECT 1 FROM [#PODateTimeMapping] AS PODM
8999 INNER JOIN #Column AS C
9000 ON PODM.NameInColumnTable = C.CName
9001 WHERE PID.DateType = PODM.NameInSourceTable)
9002 ) as p
9003
9004 UNPIVOT
9005 (
9006 TheDateTimeType FOR SourceDateTimeColumn IN
9007 (
9008 p.DateValue,
9009 p.TimeValue
9010 )
9011 ) AS up
9012
9013 OPTION(LOOP JOIN)
9014
9015 DROP TABLE #PODateTimeMapping
9016
9017 INSERT INTO #POItemDate
9018 (
9019 POItemDate_RecordID
9020 ,RequestedBookingStartDate
9021 ,RequestedBookingDate
9022 ,ShipStartDate
9023 ,ShipEndDate
9024 ,RequestedPickupStartDate
9025 ,RequestedPickupDate
9026 ,RequestedDeliveryStartDate
9027 ,RequestedDeliveryDate
9028 )
9029 SELECT
9030 RecordID
9031 ,P.[RequestedBookingStartDate]
9032 ,P.[RequestedBookingDate]
9033 ,P.[ShipStartDate]
9034 ,P.[ShipEndDate]
9035 ,P.[RequestedPickupStartDate]
9036 ,P.[RequestedPickupDate]
9037 ,P.[RequestedDeliveryStartDate]
9038 ,P.[RequestedDeliveryDate]
9039 FROM
9040 (
9041
9042 SELECT R.RecordID, UPOD.DateTimeType, MIN(UPOD.DateTimeValue) AS DateTimeValue
9043 FROM #Row AS R
9044 INNER JOIN dbo.POItem AS I WITH (NOLOCK)
9045 ON R.POItemID = I.POItemID
9046 INNER JOIN [#UnpivotedPODates] AS UPOD
9047 ON I.POItemID = UPOD.POItemID
9048 GROUP BY R.RecordID, UPOD.DateTimeType
9049 ) AS UP
9050 PIVOT
9051 (
9052 MIN(UP.DateTimeValue) FOR UP.DateTimeType IN
9053 (
9054 [RequestedBookingStartDate]
9055 ,[RequestedBookingDate]
9056 ,[ShipStartDate]
9057 ,[ShipEndDate]
9058 ,[RequestedPickupStartDate]
9059 ,[RequestedPickupDate]
9060 ,[RequestedDeliveryStartDate]
9061 ,[RequestedDeliveryDate]
9062 )
9063 ) AS P
9064 END
9065
9066 IF @ProcessPOItemReference =1
9067 BEGIN
9068 CREATE TABLE #TempItemRefs
9069 (
9070 RecordID INT,
9071 RefNumber NVARCHAR(255),
9072 RefType VARCHAR(50)
9073 )
9074
9075 INSERT INTO #TempItemRefs
9076 (
9077 RecordID,
9078 RefNumber,
9079 RefType
9080 )
9081 SELECT
9082 R.RecordID,
9083 Ref.ReferenceNumber,
9084 ITR.ReferenceType
9085 FROM #Row AS R
9086 INNER JOIN dbo.POItemReference AS ITR WITH (NOLOCK)
9087 ON R.POItemID = ITR.POItemID
9088 INNER JOIN NTSR.dbo.DimReference AS Ref WITH (NOLOCK)
9089 ON Ref.KeyReferenceID = ITR.KeyReferenceID
9090 UNION ALL
9091 SELECT
9092 R.RecordID,
9093 Ref.ReferenceNumber,
9094 POR.ReferenceType
9095 FROM #Row AS R
9096 INNER JOIN dbo.POrderReference AS POR WITH (NOLOCK)
9097 ON R.POID = POR.POrderID
9098 INNER JOIN NTSR.dbo.DimReference AS Ref WITH (NOLOCK)
9099 ON Ref.KeyReferenceID = POR.KeyReferenceID
9100
9101 INSERT INTO #POItemReference
9102 (
9103 POItemReference_RecordID
9104 ,POLineNumber
9105 ,VendorPONumber
9106 ,VendorLineNumber
9107 ,CustomerPONumber
9108 ,BuyerID
9109 )
9110 SELECT
9111 RecordID,
9112 P.[CustomerPOLineNumber],
9113 P.[Vendor PO],
9114 P.[Vendor Line Number],
9115 P.[CustomerPONumber],
9116 p.[Buyer ID #]
9117 FROM
9118 (
9119 SELECT RecordID, RefNumber, RefType
9120 FROM #TempItemRefs
9121 ) AS UP
9122 PIVOT
9123 (
9124 MAX(UP.RefNumber) FOR RefType IN
9125 (
9126 [CustomerPOLineNumber],
9127 [Vendor PO],
9128 [Vendor Line Number],
9129 [CustomerPONumber],
9130 [Buyer ID #]
9131 )
9132 ) AS P
9133
9134 END
9135
9136 IF @ProcessCOrderDates = 1
9137 BEGIN
9138 CREATE TABLE #CorderDateMapping
9139 (
9140 NameInColumnTable VARCHAR(50),
9141 NameInSourceTable VARCHAR(50)
9142 )
9143
9144 Create Table #UnpivotedCOrderDates
9145 (
9146 POItemID INT,
9147 DateType VARCHAR(100),
9148 DateValue INT
9149 )
9150 INSERT INTO [#CorderDateMapping] (NameInColumnTable,NameInSourceTable)
9151 SELECT 'RecBookingDate', 'ShippableOrderRecBookingDate'
9152
9153 INSERT INTO [#UnpivotedCOrderDates] (POItemID,DateType,DateValue)
9154 SELECT
9155 UP.POItemID,
9156 CASE UP.SourceDateTimeColumn
9157 WHEN 'TimeValue' THEN REPLACE(UP.DateType,'Date','Time')
9158 ELSE UP.DateType END,
9159 UP.TheDateTimeType
9160
9161 FROM
9162 (
9163 SELECT TOP 1 CITEM.POItemID, COrderDate.DateType, MIN(COrderDate.DateValue) AS DateValue, COrderDate.TimeValue
9164 FROM #Row AS R
9165 INNER JOIN dbo.COItem_PO CITEM WITH (NOLOCK) ON R.POItemID = CITEM.POItemID
9166 INNER JOIN dbo.COItem OITEM WITH (NOLOCK) ON CITEM.COItemID = OITEM.COItemID
9167 INNER JOIN dbo.COSDetail COSD WITH (NOLOCK) ON COSD.COSDetailID = OITEM.COSDetailID
9168 INNER JOIN dbo.COService S ON S.COServiceID = COSD.COServiceID AND S.SourceTypeID = 6
9169 INNER JOIN dbo.COrderDate AS COrderDate WITH (NOLOCK) ON S.COrderID = COrderDate.COrderID AND COrderDate.DateType = 'ShippableOrderRecBookingDate'
9170 WHERE EXISTS (SELECT 1 FROM [#CorderDateMapping] AS CODM
9171 INNER JOIN #Column AS C
9172 ON CODM.NameInColumnTable = C.CName
9173 WHERE COrderDate.DateType = CODM.NameInSourceTable)
9174 GROUP BY CITEM.POItemID, COrderDate.DateType, DateValue, COrderDate.TimeValue
9175 ) as P
9176
9177 UNPIVOT
9178 (
9179 TheDateTimeType FOR SourceDateTimeColumn IN
9180 (
9181 P.DateValue,
9182 P.TimeValue
9183 )
9184 ) AS up
9185
9186 OPTION(LOOP JOIN)
9187
9188 DROP TABLE #CorderDateMapping
9189
9190 INSERT INTO #COrderDate
9191 (
9192 COrderDate_RecordID
9193 ,RecBookingDate
9194 )
9195 SELECT
9196 RecordID
9197 ,P.[ShippableOrderRecBookingDate]
9198 FROM
9199 (
9200 SELECT R.RecordID, UPOD.DateType, MIN(UPOD.DateValue) AS DateValue
9201 FROM #Row AS R
9202 INNER JOIN [#UnpivotedCOrderDates] AS UPOD
9203 ON R.POItemID = UPOD.POItemID
9204 GROUP BY R.RecordID, UPOD.DateType
9205 ) AS UP
9206 PIVOT
9207 (
9208 MIN(UP.DateValue) FOR UP.DateType IN
9209 (
9210 [ShippableOrderRecBookingDate]
9211 )
9212 ) AS P
9213 END
9214
9215 IF @ProcessCustomsCargoWise = 1
9216 BEGIN
9217 CREATE TABLE #TempCustRefs
9218 (
9219 RecordID INT,
9220 RefNumber NVARCHAR(255),
9221 RefType VARCHAR(50)
9222 )
9223
9224 INSERT INTO #TempCustRefs
9225 (
9226 RecordID,
9227 RefNumber,
9228 RefType
9229 )
9230 SELECT
9231 R.RecordID,
9232 Ref.ReferenceNumber,
9233 CS.ReferenceSubType
9234 FROM #Row AS R
9235 INNER JOIN dbo.CustomsReference AS CS WITH (NOLOCK)
9236 ON R.COServiceID = CS.COServiceID
9237 INNER JOIN NTSR.dbo.DimReference AS Ref WITH (NOLOCK)
9238 ON Ref.KeyReferenceID = CS.KeyReferenceID
9239 INNER JOIN dbo.OrderParty O
9240 ON CS.OrderPartyID = O.OrderPartyID
9241 WHERE CS.ReferenceSubType IN ('Agriculture Hold Date','OGA/FDA Exam Date')
9242
9243
9244 INSERT INTO #CargoWiseCustoms
9245 (
9246 CargoWise_RecordID
9247 ,AgricultureHoldDate
9248 ,OGAFDAExamDate
9249 )
9250 SELECT
9251 RecordID,
9252 CASE WHEN ISDATE(P.[Agriculture Hold Date])= 1 THEN
9253 CAST(P.[Agriculture Hold Date] AS DATETIME)
9254 ELSE NULL END AS AgricultureHold,
9255 CASE WHEN ISDATE(P.[OGA/FDA Exam Date])= 1 THEN
9256 CAST(P.[OGA/FDA Exam Date] AS DATETIME)
9257 ELSE NULL END AS OGAFDAExam
9258 FROM
9259 (
9260 SELECT RecordID, RefNumber, RefType
9261 FROM #TempCustRefs
9262 ) AS UP
9263 PIVOT
9264 (
9265 MAX(UP.RefNumber) FOR RefType IN
9266 (
9267 [Agriculture Hold Date],
9268 [OGA/FDA Exam Date]
9269 )
9270 ) AS P
9271 END
9272 --END PurchaseOrder related stuff
9273
9274 -- ========================================================================================================
9275 -- Build @SQL
9276 -- ========================================================================================================
9277
9278 --PRINT 'UPDATE #Row.CHRNumber FOR LevelNumber = 2'
9279
9280IF @ReportLevel & 1 > 0 BEGIN
9281 UPDATE R SET CHRNumber = CG.PrimaryLoadNumber
9282 FROM #Row AS R
9283 INNER JOIN COSGroup AS CG WITH (NOLOCK)
9284 ON R.COSGroupID = CG.COSGroupID
9285 WHERE R.LevelNumber = 2
9286END
9287
9288If @ReportLevel = 128 BEGIN
9289 UPDATE R Set CHRNumber = NULL
9290 FROM #Row R
9291 WHERE R.LevelNumber = 3
9292END
9293
9294IF @ProcessDisplayShipmentNumbers = 1
9295 BEGIN
9296 UPDATE #Row
9297 SET DisplayCustomerOrderNumber = CASE WHEN CustomerOrderNumber <> -1 THEN CAST(CustomerOrderNumber AS VARCHAR(16)) ELSE '' END,
9298 DisplayLoadNumber = CASE WHEN DisplayLoadNumber IS NOT NULL THEN CAST(DisplayLoadNumber AS VARCHAR(512))
9299 WHEN CHRNumber = CustomerOrderNumber AND LoadNumber > 0 THEN CAST(LoadNumber AS VARCHAR(512))
9300 WHEN CHRNumber = CustomerOrderNumber AND LoadNumber = -1 THEN ''
9301 ELSE CAST(CHRNumber AS VARCHAR(512)) END
9302 FROM #Row
9303END
9304
9305IF @ProcessOrderedSpace = 1
9306 BEGIN
9307
9308 IF @SummarizeShipment = 1
9309 BEGIN
9310 INSERT INTO #OrderedSpace
9311 (
9312 OrderedSpace_RecordID,
9313 OrderedSpace
9314 )
9315 SELECT
9316 R.RecordID,
9317 SUM(L.OrderedSpace)
9318 FROM #Row AS R
9319 INNER JOIN dbo.COLocation AS L WITH (NOLOCK)
9320 ON R.DestCOLocationID = L.COLocationID
9321 GROUP BY R.RecordID
9322 END
9323 ELSE
9324 BEGIN
9325 INSERT INTO #OrderedSpace
9326 (
9327 OrderedSpace_RecordID,
9328 OrderedSpace
9329 )
9330 SELECT
9331 R.RecordID,
9332 L.OrderedSpace
9333 FROM #Row AS R
9334 INNER JOIN dbo.COLocation AS L WITH (NOLOCK)
9335 ON R.DestCOLocationID = L.COLocationID
9336 END
9337END
9338
9339 SET @SQL =
9340 ' FROM (SELECT RecordID, CAST(CHRNumber AS VARCHAR(512)) AS CHRNumber, MAX(DisplayCustomerOrderNumber) AS DisplayCustomerOrderNumber, MAX(DisplayLoadNumber) AS DisplayLoadNumber, MAX(ShipmentMode) AS ShipmentMode, ' +
9341 ' CAST(MAX(CAST(LogisticFlg AS INT)) AS BIT) AS LogisticFlg FROM #Row ' +
9342 ' GROUP BY RecordID, CHRNumber) AS Row '
9343
9344 IF @ProcessItems = 1
9345 BEGIN
9346 -- create clusteredINDEX Item_RecordID ON #Item(Item_RecordID)
9347 SET @sql = @sql + ' LEFT OUTER JOIN #Item ON RecordID = Item_RecordID '
9348 END
9349
9350 IF @ProcessFlatbed = 1
9351 BEGIN
9352 SET @Sql = @sql + ' LEFT OUTER JOIN #ItemFlatbed ON RecordID = ItemFlatbed_RecordID AND ItemId = ItemFlatbedID '
9353 END
9354
9355 --PRINT 'Replace Accessorial/EndCust Charge Buckets'
9356
9357 IF EXISTS(SELECT 1 FROM #Column AS C WHERE C.CName IN ('AccessorialOtherDetails.*','EndCustAccessorialDetails.*'))
9358 BEGIN
9359-- CREATE CLUSTERED INDEX INX_AccessorialChargeDescription_RecordID ON #AccessorialChargeDescription(AccessorialChargeDescription_RecordID)
9360 -- SCHOSCO: fixed pivot problem with financialtype
9361 SET @Collist = NULL
9362 SELECT @Collist = ISNULL(@Collist + ',', '') + '[' + CONVERT(VARCHAR(MAX), [Description]) + ']'
9363 FROM #AccessorialChargeDescription
9364 WHERE AccessorialChargeFinancialType = 'ActCharge'
9365 GROUP BY [Description]
9366
9367 IF @Collist IS NOT NULL
9368 BEGIN
9369 SET @SelectClause = REPLACE(@SelectClause, 'AccessorialOtherDetails.*', @Collist)
9370 END
9371 ELSE
9372 BEGIN
9373 -- remove placeholder from select so dynamic sql doesn't blow up
9374 SET @SelectClause = REPLACE(@SelectClause, 'AccessorialOtherDetails.*,', '')
9375 SET @SelectClause = REPLACE(@SelectClause, ',AccessorialOtherDetails.*', '')
9376 SET @SelectClause = REPLACE(@SelectClause, 'AccessorialOtherDetails.*', '')
9377 END
9378
9379 SET @Collist2 = NULL
9380 SELECT @Collist2 = ISNULL(@Collist2 + ',', '') + '[' + CONVERT(VARCHAR(MAX), [Description]) + ']'
9381 FROM #AccessorialChargeDescription
9382 WHERE AccessorialChargeFinancialType = 'ECC'
9383 GROUP BY [Description]
9384
9385 IF @Collist2 IS NOT NULL
9386 BEGIN
9387 SET @SelectClause = REPLACE(@SelectClause, 'EndCustAccessorialDetails.*', @Collist2)
9388
9389 IF @Collist IS NULL
9390 BEGIN
9391 SET @Collist = @Collist2
9392 END
9393 ELSE
9394 BEGIN
9395 SET @Collist = @Collist + ',' + @Collist2
9396 END
9397 END
9398 ELSE
9399 BEGIN
9400 SET @SelectClause = REPLACE(@SelectClause, 'EndCustAccessorialDetails.*,', '')
9401 SET @SelectClause = REPLACE(@SelectClause, ',EndCustAccessorialDetails.*', '')
9402 SET @SelectClause = REPLACE(@SelectClause, 'EndCustAccessorialDetails.*', '')
9403 END
9404
9405 IF @Collist IS NOT NULL
9406 BEGIN
9407 SET @sql = @sql + ' LEFT OUTER JOIN (SELECT AccessorialChargeDescription_RecordID, Amount, Description FROM #AccessorialChargeDescription) AS AccessorialChargeDescription
9408 ON RecordID = AccessorialChargeDescription.AccessorialChargeDescription_RecordID
9409 PIVOT(
9410 SUM (AccessorialChargeDescription.Amount) FOR AccessorialChargeDescription.Description IN ( '+@collist+')
9411 ) AS AccessorialOtherDetails '
9412 END
9413 END
9414
9415 --PRINT 'REPLACE ShipmentAlerts.*'
9416
9417 IF EXISTS (SELECT 1 FROM #Column AS C WHERE C.CName = 'ShipmentAlerts.*')
9418 BEGIN
9419 SET @Collist = NULL
9420
9421 SELECT @Collist = ISNULL(@Collist + ',', '') + '[' + convert(varchar(max), [Description]) + ']' FROM #Alert GROUP BY [Description]
9422
9423 IF @Collist IS NOT NULL
9424 BEGIN
9425 -- need to prefix column select with pivot alias since it's possible
9426-- that dynamic pivots could have same column name as other columns in select clause
9427 SET @SelectClause = REPLACE(@SelectClause, 'ShipmentAlerts.*', @Collist)
9428 SET @SQL = @SQL + ' LEFT OUTER JOIN #Alert AS Alert ON RecordID = Alert.Alert_RecordID
9429 PIVOT (
9430 MAX(EnteredDate) FOR Alert.Description IN (' + @Collist + ')
9431 ) AS ShipmentAlerts '
9432 END
9433 ELSE
9434 BEGIN
9435 SET @SelectClause = REPLACE(@SelectClause, 'ShipmentAlerts.*,', '')
9436 SET @SelectClause = REPLACE(@SelectClause, ',ShipmentAlerts.*', '')
9437 SET @SelectClause = REPLACE(@SelectClause, 'ShipmentAlerts.*', '')
9438 END
9439 END
9440
9441 --PRINT 'REPLACE ClosedAlerts.*'
9442
9443 IF EXISTS (SELECT 1 FROM #Column AS C WHERE C.CName = 'ClosedAlerts.*')
9444 BEGIN
9445 SET @Collist = NULL
9446
9447 SELECT @Collist = ISNULL(@Collist + ',', '') + '[' + convert(varchar(max), [Description]) + ']' FROM #ClosedAlert GROUP BY [Description]
9448
9449 IF @Collist IS NOT NULL
9450 BEGIN
9451 -- need to prefix column select with pivot alias since it's possible
9452 -- that dynamic pivots could have same column name as other columns in select clause
9453 SET @SelectClause = REPLACE(@SelectClause, 'ClosedAlerts.*', @Collist)
9454 SET @SQL = @SQL + ' LEFT OUTER JOIN #ClosedAlert AS ClosedAlert ON RecordID = ClosedAlert.ClosedAlert_RecordID
9455 PIVOT (
9456 MAX(EnteredDate) FOR ClosedAlert.Description IN (' + @Collist + ')
9457 ) AS ClosedAlerts '
9458 END
9459 ELSE
9460 BEGIN
9461 SET @SelectClause = REPLACE(@SelectClause, 'ClosedAlerts.*,', '')
9462 SET @SelectClause = REPLACE(@SelectClause, ',ClosedAlerts.*', '')
9463 SET @SelectClause = REPLACE(@SelectClause, 'ClosedAlerts.*', '')
9464 END
9465 END
9466
9467 --PRINT 'Replace Ref Buckets'
9468
9469 IF EXISTS
9470 (
9471 SELECT 1
9472 FROM #Column
9473 WHERE CName IN
9474 (
9475 'ShipmentRefNums',
9476 'PayerRefNums',
9477 'OrigRefNums',
9478 'DestRefNums',
9479 'CustRefNum',
9480 'PayerRefNum',
9481 'ShipperReference',
9482 'OrderNum',
9483 'MBOL',
9484 'HBOL',
9485 'SSLineBOL',
9486 'ConfirmationNumber',
9487 'CarrierProNum',
9488 'CustLoadNum',
9489 'SubHBOL',
9490 'MasterPO',
9491 'PickupNum',
9492 'DeliveryNum',
9493 'BOL',
9494 'AirlineWayBill',
9495 'MasterAWB',
9496 'ActArriDt',
9497 'ActDepDt',
9498 'BOLREF',
9499 'CCTR',
9500 'CITTN',
9501 'CON',
9502 'CRID',
9503 'DEL',
9504 'DIST',
9505 'DIV',
9506 'FDA',
9507 'GL',
9508 'JNO',
9509 'LIC',
9510 'LOAD',
9511 'MBOLREF',
9512 'MREF',
9513 'ORD',
9514 'OrderID',
9515 'PO',
9516 'PRO',
9517 'PU',
9518 'SEAL',
9519 'SHID',
9520 'SHIPWITH'
9521 )
9522 )
9523
9524 BEGIN
9525 --CREATE CLUSTERED INDEX INX_REF_RecordID ON #Ref(Ref_RecordID)
9526 CREATE INDEX INX_Ref_ReferenceType ON #Ref(ReferenceType)
9527 --CREATE CLUSTERED INDEX INX_ITEMREF_RecordID ON [#ItemRef](ItemRef_RecordID)
9528 CREATE INDEX INX_ItemRef_ItemReferenceType ON #ItemRef(ItemReferenceType)
9529
9530 DECLARE @RefTypeSelect VARCHAR(MAX)
9531 SET @Collist = NULL
9532
9533 SELECT
9534 @Collist = ISNULL(@Collist + ',', '') + '[' + convert(varchar(max), [ReferenceType]) + ']'
9535 FROM #Ref
9536 GROUP BY ReferenceType
9537
9538 --PRINT '@Collist = ' + @Collist
9539
9540 IF EXISTS (SELECT 1 FROM #Column WHERE CName = 'ShipmentRefNums')
9541 BEGIN
9542
9543 SELECT @RefTypeSelect = ISNULL(@RefTypeSelect + ',', '') + '[' + convert(varchar(max), [ReferenceType]) + ']'
9544 FROM #Ref
9545 WHERE ReferenceSubType = 'Shipment'
9546 GROUP BY ReferenceType
9547
9548 IF @RefTypeSelect IS NOT NULL
9549 BEGIN
9550 SET @SelectClause = REPLACE(@SelectClause, 'ShipmentRefNums', @RefTypeSelect)
9551 END
9552 ELSE
9553 BEGIN
9554 SET @SelectClause = REPLACE(@SelectClause, 'ShipmentRefNums,', '')
9555 SET @SelectClause = REPLACE(@SelectClause, ',ShipmentRefNums', '')
9556 SET @SelectClause = REPLACE(@SelectClause, 'ShipmentRefNums', '')
9557 END
9558 END
9559
9560 IF EXISTS (SELECT 1 FROM #Column WHERE CName = 'PayerRefNums')
9561 BEGIN
9562 SET @RefTypeSelect = NULL
9563
9564 SELECT @RefTypeSelect = ISNULL(@RefTypeSelect + ',', '') + '[' + convert(varchar(max), [ReferenceType]) + ']'
9565 FROM #Ref
9566 WHERE ReferenceSubType = 'Payer'
9567 GROUP BY ReferenceType
9568
9569 IF @RefTypeSelect IS NOT NULL
9570 BEGIN
9571 SET @SelectClause = REPLACE(@SelectClause, 'PayerRefNums', @RefTypeSelect)
9572 END
9573 ELSE
9574 BEGIN
9575 SET @SelectClause = REPLACE(@SelectClause, 'PayerRefNums,', '')
9576 SET @SelectClause = REPLACE(@SelectClause, ',PayerRefNums', '')
9577 SET @SelectClause = REPLACE(@SelectClause, 'PayerRefNums', '')
9578 END
9579 END
9580
9581 IF EXISTS (SELECT 1 FROM #Column WHERE CName = 'OrigRefNums')
9582 BEGIN
9583 SET @RefTypeSelect = NULL
9584
9585 SELECT @RefTypeSelect = ISNULL(@RefTypeSelect + ',', '') + '[' + convert(varchar(max), [ReferenceType]) + ']'
9586 FROM #Ref
9587 WHERE ReferenceSubType = 'Origin'
9588 GROUP BY ReferenceType
9589
9590 IF @RefTypeSelect IS NOT NULL
9591 BEGIN
9592 SET @SelectClause = REPLACE(@SelectClause, 'OrigRefNums', @RefTypeSelect)
9593 END
9594 ELSE
9595 BEGIN
9596 SET @SelectClause = REPLACE(@SelectClause, 'OrigRefNums,', '')
9597 SET @SelectClause = REPLACE(@SelectClause, ',OrigRefNums', '')
9598 SET @SelectClause = REPLACE(@SelectClause, 'OrigRefNums', '')
9599 END
9600 END
9601
9602 IF EXISTS (SELECT 1 FROM #Column WHERE CName = 'DestRefNums')
9603 BEGIN
9604 SET @RefTypeSelect = NULL
9605
9606 SELECT @RefTypeSelect = ISNULL(@RefTypeSelect + ',', '') + '[' + convert(varchar(max), [ReferenceType]) + ']'
9607 FROM #Ref
9608 WHERE ReferenceSubType = 'Destination'
9609 GROUP BY ReferenceType
9610
9611 IF @RefTypeSelect IS NOT NULL
9612 BEGIN
9613 SET @SelectClause = REPLACE(@SelectClause, 'DestRefNums', @RefTypeSelect)
9614 END
9615 ELSE
9616 BEGIN
9617 SET @SelectClause = REPLACE(@SelectClause, 'DestRefNums,', '')
9618 SET @SelectClause = REPLACE(@SelectClause, ',DestRefNums', '')
9619 SET @SelectClause = REPLACE(@SelectClause, 'DestRefNums', '')
9620 END
9621 END
9622
9623 IF @Collist IS NOT NULL
9624 BEGIN
9625 SET @SQL = @SQL + ' LEFT OUTER JOIN (SELECT Ref_RecordID, ReferenceType, ReferenceNumber
9626 FROM #Ref) AS Ref ON RecordID = Ref.Ref_RecordID
9627 PIVOT (
9628 MAX(Ref.ReferenceNumber) FOR Ref.ReferenceType IN (' + @Collist + ')
9629 ) AS RefPivot '
9630 END
9631 END
9632
9633 --PRINT 'Replace ItemRef Bucket'
9634
9635 IF EXISTS
9636 (
9637 SELECT 1
9638 FROM #Column
9639 WHERE CName IN
9640 (
9641 'UPC',
9642 'NMFC',
9643 'OrigninalNMFC',
9644 'CustSpecific1',
9645 'CustSpecific2',
9646 'ProductCode',
9647 'PLU',
9648 'EAN',
9649 'HTCode',
9650 'VenderPO',
9651 'JobNum',
9652 'PONum',
9653 'LotNumber',
9654 'ItemRefNums'
9655 )
9656 )
9657
9658 BEGIN
9659 DECLARE @ItemRefTypeSelect VARCHAR(MAX)
9660 SET @Collist = NULL
9661
9662 SELECT @Collist = ISNULL(@Collist + ',', '') + '[' + convert(varchar(max), [ItemReferenceType]) + ']'
9663 FROM #ItemRef
9664 GROUP BY ItemReferenceType
9665
9666 IF EXISTS (SELECT 1 FROM #Column WHERE CName = 'ItemRefNums')
9667 BEGIN
9668
9669 SELECT @ItemRefTypeSelect = ISNULL(@ItemRefTypeSelect + ',', '') + '[' + convert(varchar(max), [ItemReferenceType]) + ']'
9670 FROM #ItemRef
9671 WHERE ItemReferenceSubType = 'Item'
9672 GROUP BY ItemReferenceType
9673
9674 IF @ItemRefTypeSelect IS NOT NULL
9675 BEGIN
9676 SET @SelectClause = REPLACE(@SelectClause, 'ItemRefNums', @ItemRefTypeSelect)
9677 END
9678 ELSE
9679 BEGIN
9680 --PRINT 'SELECT CLAUSE BEFORE: ' + @SelectClause
9681 SET @SelectClause = REPLACE(@SelectClause, 'ItemRefNums,', '')
9682 SET @SelectClause = REPLACE(@SelectClause, ',ItemRefNums', '')
9683 SET @SelectClause = REPLACE(@SelectClause, 'ItemRefNums', '')
9684 --PRINT 'SELECT CLAUSE AFTER: ' + @SelectClause
9685 END
9686 END
9687
9688 IF @Collist IS NOT NULL
9689 BEGIN
9690 SET @SQL = @SQL + ' LEFT OUTER JOIN (SELECT ItemRef_RecordID, ItemRef_itemID, ItemReferenceType, ItemReferenceNumber
9691 FROM #ItemRef) AS IRef ON RecordID = IRef.ItemRef_RecordID AND ItemID = ItemRef_itemID
9692 PIVOT (
9693 MAX(IRef.ItemReferenceNumber) FOR IRef.ItemReferenceType IN (' + @Collist + ')
9694 ) AS ItemRefPivot '
9695 END
9696 END
9697
9698 --PRINT 'REPLACE Payers'
9699
9700 IF @ProcessPayers = 1
9701BEGIN
9702
9703 DECLARE @MaxPayer INT
9704 SELECT @MaxPayer = MAX(PayerNumber) FROM #Payer
9705 SET @MaxPayer = ISNULL(@MaxPayer, 1)
9706
9707 DECLARE @Counter INT
9708 SET @Counter = 1
9709
9710 DECLARE
9711 @PayerNameSelect VARCHAR(MAX),
9712@PayerAddress1Select VARCHAR(MAX),
9713 @PayerAddress2Select VARCHAR(MAX),
9714 @PayerCitySelect VARCHAR(MAX),
9715 @PayerStateSelect VARCHAR(MAX),
9716 @PayerZipSelect VARCHAR(MAX),
9717 @PayerLocationIDSelect VARCHAR(MAX),
9718 @Number VARCHAR(3),
9719 @PayerAlias VARCHAR(4),
9720 @PayerJoinClause VARCHAR(MAX),
9721 @GlobalPayerFlag VARCHAR(16) = '__CHRW_ONLINE_'
9722
9723 WHILE @Counter <= @MaxPayer
9724 BEGIN
9725 SET @Number = CONVERT(VARCHAR(3), @Counter)
9726 SET @PayerAlias = 'P' + @Number
9727
9728 SET @PayerNameSelect = ISNULL(@PayerNameSelect + ',','') + @PayerAlias + '.PayerName AS [' + @GlobalPayerFlag + 'Payer' + @Number + ' Name]'
9729 SET @PayerAddress1Select = ISNULL(@PayerAddress1Select + ',','') + @PayerAlias + '.PayerAddress1 AS [' + @GlobalPayerFlag + 'Payer' + @Number + ' Address1]'
9730 SET @PayerAddress2Select = ISNULL(@PayerAddress2Select + ',','') + @PayerAlias + '.PayerAddress2 AS [' + @GlobalPayerFlag + 'Payer' + @Number + ' Address2]'
9731 SET @PayerCitySelect = ISNULL(@PayerCitySelect + ',','') + @PayerAlias + '.PayerCity AS [' + @GlobalPayerFlag + 'Payer' + @Number + ' City]'
9732 SET @PayerStateSelect = ISNULL(@PayerStateSelect + ',','') + @PayerAlias + '.PayerState AS [' + @GlobalPayerFlag + 'Payer' + @Number + ' State]'
9733 SET @PayerZipSelect = ISNULL(@PayerZipSelect + ',','') + @PayerAlias + '.PayerZip AS [' + @GlobalPayerFlag + 'Payer' + @Number + ' Zip]'
9734 SET @PayerLocationIDSelect = ISNULL(@PayerLocationIDSelect + ',','') + @PayerAlias + '.PayerLocationID AS [' + @GlobalPayerFlag + 'Payer' + @Number + ' Account Code]'
9735
9736 SET @PayerJoinClause = ISNULL(@PayerJoinClause,'') + ' LEFT OUTER JOIN #Payer AS ' + @PayerAlias +
9737 ' ON RecordID = ' + @PayerAlias + '.Payer_RecordID ' +
9738 ' AND ' + @PayerAlias + '.PayerNumber = ' + @Number
9739
9740 SET @Counter = @Counter + 1
9741 END
9742
9743 SET @SelectClause = REPLACE(@SelectClause, 'PayerName', @PayerNameSelect)
9744 SET @SelectClause = REPLACE(@SelectClause, 'PayerAddress1', @PayerAddress1Select)
9745 SET @SelectClause = REPLACE(@SelectClause, 'PayerAddress2', @PayerAddress2Select)
9746SET @SelectClause = REPLACE(@SelectClause, 'PayerCity', @PayerCitySelect)
9747 SET @SelectClause = REPLACE(@SelectClause, 'PayerState', @PayerStateSelect)
9748 SET @SelectClause = REPLACE(@SelectClause, 'PayerZip', @PayerZipSelect)
9749 SET @SelectClause = REPLACE(@SelectClause, 'PayerLocationID', @PayerLocationIDSelect)
9750
9751 SET @SQL = @SQL + @PayerJoinClause
9752 END
9753 IF EXISTS(SELECT 1 FROM #Column AS C WHERE C.CName IN ('OrigSpecialInstructions', 'DestSpecialinstructions'))
9754 BEGIN
9755 -- CREATE CLUSTERED INDEX SpecialInstructions_RecordID ON #SpecialInstructions(SpecialInstructions_RecordID)
9756 SET @sql = @sql + ' LEFT OUTER JOIN #SpecialInstructions ON RecordID = SpecialInstructions_RecordID '
9757 END
9758 IF @ProcessCustomerLocations = 1
9759 BEGIN
9760 -- create clusteredINDEX CustomerLocation_RecordID ON #CustomerLocation(CustomerLocation_RecordID)
9761 SET @sql = @sql + ' LEFT OUTER JOIN #CustomerLocation ON RecordID = CustomerLocation_RecordID '
9762 END
9763 IF @ProcessStopNums = 1
9764 BEGIN
9765 SET @sql = @sql + ' LEFT OUTER JOIN #StopNums WITH (NOLOCK) ON RecordID = StopNums_RecordID '
9766 END
9767 IF @ProcessMisc = 1
9768 BEGIN
9769 -- create clusteredINDEX Misc_RecordID ON #Misc(Misc_RecordID)
9770 SET @sql = @sql + ' LEFT OUTER JOIN #Misc ON RecordID = Misc_RecordID '
9771END
9772 IF @ProcessMiscDates = 1
9773 BEGIN
9774 -- create clusteredINDEX MiscDate_RecordID ON #MiscDate(MiscDate_RecordID)
9775 SET @sql = @sql + ' LEFT OUTER JOIN #MiscDate ON RecordID = MiscDate_RecordID '
9776 END
9777 IF @ProcessInterLocations = 1
9778 BEGIN
9779 -- create clusteredINDEX InterLocation_RecordID ON #InterLocation(InterLocation_RecordID)
9780 SET @sql = @sql + ' LEFT OUTER JOIN #InterLocation ON RecordID = InterLocation_RecordID '
9781 END
9782 IF @ProcessFUDates = 1
9783 BEGIN
9784 -- create clusteredINDEX FUDate_RecordID ON #FUDate(FUDate_RecordID)
9785 SET @sql = @sql + ' LEFT OUTER JOIN #FUDate ON RecordID = FUDate_RecordID '
9786 END
9787 IF @ProcessLFUDates = 1
9788 BEGIN
9789 -- create clusteredINDEX LFUDate_RecordID ON #LFUDate(LFUDate_RecordID)
9790 SET @sql = @sql + ' LEFT OUTER JOIN #LFUDate ON RecordID = LFUDate_RecordID '
9791 END
9792 IF @ProcessInvoices = 1
9793 BEGIN
9794 -- create clusteredINDEX Invoice_RecordID ON #Invoice(Invoice_RecordID)
9795 SET @sql = @sql + ' LEFT OUTER JOIN #Invoice ON RecordID = Invoice_RecordID '
9796 END
9797 IF @ProcessItemSummaries = 1
9798 BEGIN
9799 -- create clusteredINDEX ItemSummary_RecordID ON #ItemSummary(ItemSummary_RecordID)
9800 SET @sql = @sql + ' LEFT OUTER JOIN #ItemSummary ON RecordID = ItemSummary_RecordID '
9801 END
9802 IF @ProcessDriverTixSummaries = 1
9803 BEGIN
9804 -- create clusteredINDEX DriverTixSummary_RecordID ON #DriverTixSummary(DriverTixSummary_RecordID)
9805 SET @sql = @sql + ' LEFT OUTER JOIN #DriverTixSummary ON RecordID = DriverTixSummary_RecordID '
9806 END
9807 IF @ProcessItemSummaryTexts = 1
9808 BEGIN
9809 -- create clusteredINDEX ItemSummaryText_RecordID ON #ItemSummaryText(ItemSummaryText_RecordID)
9810 SET @sql = @sql + ' LEFT OUTER JOIN #ItemSummaryText ON RecordID = ItemSummaryText_RecordID '
9811 END
9812 IF @ProcessComments = 1
9813 BEGIN
9814 -- create clusteredINDEX Comment_RecordID ON #Comment(Comment_RecordID)
9815 SET @sql = @sql + ' LEFT OUTER JOIN #Comment ON RecordID = Comment_RecordID '
9816 END
9817 IF @ProcessCOServices = 1
9818 BEGIN
9819 -- create clusteredINDEX COService_RecordID ON #COService(COService_RecordID)
9820 SET @sql = @sql + ' LEFT OUTER JOIN #COService ON RecordID = COService_RecordID '
9821 END
9822
9823 IF @ProcessCompliance = 1
9824 BEGIN
9825 SET @sql = @sql + ' LEFT OUTER JOIN #Compliance ON RecordID = Compliance_RecordID '
9826 END
9827
9828 IF @ProcessLastInvoices = 1
9829 BEGIN
9830 -- create clusteredINDEX LastInvoice_RecordID ON #LastInvoice(LastInvoice_RecordID)
9831SET @sql = @sql + ' LEFT OUTER JOIN #LastInvoice ON RecordID = LastInvoice_RecordID '
9832 END
9833 IF @ProcessLastEvents = 1
9834 BEGIN
9835 -- create clusteredINDEX LastEvent_RecordID ON #LastEvent(LastEvent_RecordID)
9836 SET @sql = @sql + ' LEFT OUTER JOIN #LastEvent ON RecordID = LastEvent_RecordID '
9837 END
9838 IF @ProcessLastIMDLEvents = 1
9839 BEGIN
9840 SET @sql = @sql + ' LEFT OUTER JOIN #LastIMDLEvent ON RecordID = LastIMDLEvent_RecordID '
9841 END
9842 IF @ProcessSPOrders = 1
9843 BEGIN
9844 -- create clusteredINDEX SPOrder_RecordID ON #SPOrder(SPOrder_RecordID)
9845 SET @sql = @sql + ' LEFT OUTER JOIN #SPOrder ON RecordID = SPOrder_RecordID '
9846 END
9847 IF @ProcessSPOrderIntls = 1
9848 BEGIN
9849 -- create clusteredINDEX SPOrderIntl_RecordID ON #SPOrderIntl(SPOrderIntl_RecordID)
9850 SET @sql = @sql + ' LEFT OUTER JOIN #SPOrderIntl ON RecordID = SPOrderIntl_RecordID '
9851 END
9852 IF @ProcessSPOrderOthers = 1
9853 BEGIN
9854 -- create clusteredINDEX SPOrderOther_RecordID ON #SPOrderOther(SPOrderOther_RecordID)
9855 SET @sql = @sql + ' LEFT OUTER JOIN #SPOrderOther ON RecordID = SPOrderOther_RecordID '
9856 END
9857 IF @ProcessSCACs = 1
9858 BEGIN
9859 SET @sql = @sql + ' LEFT OUTER JOIN #SCAC ON RecordID = SCAC_RecordID '
9860 END
9861 IF @ProcessCOrderDates = 1
9862 BEGIN
9863 SET @sql = @sql + ' LEFT OUTER JOIN #COrderDate ON RecordID = COrderDate_RecordID '
9864 END
9865 IF @ProcessCustoms = 1
9866 BEGIN
9867 -- create clusteredINDEX Customs_RecordID ON #Customs(Customs_RecordID)
9868 SET @sql = @sql + ' LEFT OUTER JOIN #Customs ON RecordID = Customs_RecordID '
9869 END
9870 IF @ProcessPoolCrossLocations = 1
9871 BEGIN
9872 -- create clusteredINDEX PoolCrossLocation_RecordID ON #PoolCrossLocation(PoolCrossLocation_RecordID)
9873 SET @sql = @sql + ' LEFT OUTER JOIN #PoolCrossLocation ON RecordID = PoolCrossLocation_RecordID '
9874 END
9875 IF @ProcessPoolCrossLocationDates = 1
9876 BEGIN
9877 -- create clusteredINDEX PoolCrossLocationDate_RecordID ON #PoolCrossLocationDate(PoolCrossLocationDate_RecordID)
9878 SET @sql = @sql + ' LEFT OUTER JOIN #PoolCrossLocationDate ON RecordID = PoolCrossLocationDate_RecordID '
9879 END
9880 IF @ProcessMethodsOfPayment = 1
9881 BEGIN
9882 SET @sql = @sql + ' LEFT OUTER JOIN #MethodOfPayment ON RecordID = MethodOfPayment_RecordID '
9883 END
9884
9885 -- reverse logistics
9886
9887 IF @ProcessRLOrderParty = 1
9888 BEGIN
9889 SET @sql = @sql + ' LEFT OUTER JOIN #RLOrderParty ON RecordID = RLOrderParty_RecordID '
9890 END
9891
9892 IF @ProcessRLSCAC = 1
9893 BEGIN
9894 SET @sql = @sql + ' LEFT OUTER JOIN #RLSCAC ON RecordID = RLSCAC_RecordID '
9895 END
9896
9897 IF @ProcessRLTicket = 1
9898 BEGIN
9899 SET @sql = @sql + ' LEFT OUTER JOIN #RLTicket ON RecordID = RLticket_RecordID '
9900 END
9901
9902 IF @ProcessRLTicketDate = 1
9903 BEGIN
9904 SET @sql = @sql + ' LEFT OUTER JOIN #RLTicketDate ON RecordID = RLticketDate_RecordID '
9905 END
9906
9907 IF @ProcessRLLocation = 1
9908 BEGIN
9909 SET @sql = @sql + ' LEFT OUTER JOIN #RLLocation ON RecordID = RLLocation_RecordID '
9910 END
9911
9912 IF @ProcessRLReference = 1
9913 BEGIN
9914 SET @sql = @sql + ' LEFT OUTER JOIN #RLReference ON RecordID = RLReference_RecordID '
9915 END
9916
9917 IF @ProcessRLItem = 1
9918 BEGIN
9919 SET @sql = @sql + ' LEFT OUTER JOIN #RLItem ON RecordID = RLItem_RecordID '
9920 END
9921
9922 IF @ProcessRLSummaryItem = 1
9923 BEGIN
9924 SET @sql = @sql + ' LEFT OUTER JOIN #RLSummaryItem ON RecordID = RLSummaryItem_RecordID '
9925 END
9926
9927 --PurchaseOrder related stuff
9928 IF @ProcessPOCustomer = 1
9929 BEGIN
9930 SET @sql = @sql + ' LEFT OUTER JOIN #POCustomer ON RecordID = POCustomer_RecordID '
9931 END
9932 IF @ProcessPOBuyer = 1
9933 BEGIN
9934 SET @sql = @sql + ' LEFT OUTER JOIN #POBuyer ON RecordID = POBuyer_RecordID '
9935 END
9936 IF @ProcessPOEndCustomer = 1
9937 BEGIN
9938 SET @sql = @sql + ' LEFT OUTER JOIN #POEndCustomer ON RecordID = EndCustomer_RecordID '
9939 END
9940 IF @ProcessPOImporter = 1
9941 BEGIN
9942 SET @sql = @sql + ' LEFT OUTER JOIN #POImporterofRecord ON RecordID = ImporterofRecord_RecordID '
9943 END
9944 IF @ProcessPOVendor = 1
9945 BEGIN
9946 SET @sql = @sql + ' LEFT OUTER JOIN #POVendor ON RecordID = POVendor_RecordID '
9947 END
9948 IF @ProcessPOManufacturer = 1
9949 BEGIN
9950 SET @sql = @sql + ' LEFT OUTER JOIN #POManufacturer ON RecordID = Manufacturer_RecordID '
9951 END
9952 IF @ProcessPOSeller = 1
9953 BEGIN
9954 SET @sql = @sql + ' LEFT OUTER JOIN #POSeller ON RecordID = Seller_RecordID '
9955 END
9956 IF @ProcessPOLocation = 1
9957 BEGIN
9958 SET @sql = @sql + ' LEFT OUTER JOIN #POItemLocation ON RecordID = POItemLocation_RecordID '
9959 END
9960 IF @ProcessPOItems = 1
9961 BEGIN
9962 SET @sql = @sql + ' INNER JOIN #POItems PI ON RecordID = POItems_RecordID '
9963 END
9964 IF @ProcessPOItemDate = 1
9965 BEGIN
9966 SET @sql = @sql + ' LEFT OUTER JOIN #POItemDate ON RecordID = POItemDate_RecordID '
9967 END
9968 IF @ProcessPOItemReference = 1
9969 BEGIN
9970 SET @sql = @sql + ' LEFT OUTER JOIN #POItemReference ON RecordID = POItemReference_RecordID '
9971 END
9972 IF @ProcessCustomsCargoWise = 1
9973 BEGIN
9974 SET @sql = @sql + ' LEFT OUTER JOIN #CargoWiseCustoms ON RecordID = CargoWise_RecordID '
9975 END
9976
9977 IF @ProcessDropTrailer = 1
9978 BEGIN
9979 SET @sql = @sql + ' LEFT OUTER JOIN #DropTrailer ON RecordID = DropTrailer_RecordID '
9980 END
9981
9982 IF @ProcessINCOTerm = 1
9983 BEGIN
9984 SET @sql = @sql + ' LEFT OUTER JOIN #INCOTerm ON RecordID = INCOTerm_RecordID '
9985 END
9986
9987 IF @ProcessReasonCodes = 1
9988 BEGIN
9989 SET @sql = @sql + ' LEFT OUTER JOIN #ReasonCodes ON RecordID = ReasonCodes_RecordID '
9990 END
9991
9992 IF @ProcessEPayments = 1
9993 BEGIN
9994 SET @sql = @sql + ' LEFT OUTER JOIN #EPayments ON RecordID = EPayments_RecordID '
9995 END
9996
9997 IF @ProcessLoad = 1 BEGIN
9998 SET @sql = @sql + ' LEFT OUTER JOIN #Load ON RecordID = Load_RecordID '
9999 END
10000
10001-- IF EXISTS(SELECT 1 FROM [#WantedRefTypes])
10002-- BEGIN
10003-- SET @sql = @sql + ' LEFT OUTER JOIN #Ref WITH (NOLOCK) ON RecordID = Ref_RecordID '
10004-- END
10005-- IF EXISTS(SELECT 1 FROM [#ItemRefTypes])
10006-- BEGIN
10007-- SET @sql = @sql + ' LEFT OUTER JOIN #ItemRef WITH (NOLOCK) ON RecordID = ItemRef_RecordID '
10008-- END
10009 IF EXISTS(SELECT 1 FROM #Column AS C WHERE C.CName ='AgentFee')
10010 BEGIN
10011 -- create clusteredINDEX FreightCharge_RecordID ON #FreightCharge(FreightCharge_RecordID)
10012 SET @sql = @sql + ' LEFT OUTER JOIN #AgentFee ON RecordID = AgentFee_RecordID '
10013 END
10014 IF EXISTS(SELECT 1 FROM #Column AS C WHERE C.CName ='FreightCharge')
10015 BEGIN
10016 -- create clusteredINDEX FreightCharge_RecordID ON #FreightCharge(FreightCharge_RecordID)
10017 SET @sql = @sql + ' LEFT OUTER JOIN #FreightCharge ON RecordID = FreightCharge_RecordID '
10018 END
10019 IF EXISTS(SELECT 1 FROM #Column AS C WHERE C.CName ='EndCustFreightCharge')
10020 BEGIN
10021 -- create clusteredINDEX EndCustFreightCharge_RecordID ON #EndCustFreightCharge(EndCustFreightCharge_RecordID)
10022 SET @sql = @sql + ' LEFT OUTER JOIN #EndCustFreightCharge ON RecordID = EndCustFreightCharge_RecordID '
10023 END
10024 IF EXISTS(SELECT 1 FROM #Column AS C WHERE C.CName ='AccessorialOtherCharge')
10025 BEGIN
10026 -- create clusteredINDEX AccessorialOtherCharge_RecordID ON #AccessorialOtherCharge(AccessorialOtherCharge_RecordID)
10027 SET @sql = @sql + ' LEFT OUTER JOIN #AccessorialOtherCharge AS AC ON RecordID = AccessorialOtherCharge_RecordID '
10028 END
10029 IF EXISTS(SELECT 1 FROM #Column AS C WHERE C.CName ='EndCustAccessorialCharge')
10030 BEGIN
10031 -- create clusteredINDEX EndCustAccessorialCharge_RecordID ON #EndCustAccessorialCharge(EndCustAccessorialCharge_RecordID)
10032 SET @sql = @sql + ' LEFT OUTER JOIN #EndCustAccessorialCharge ON RecordID = EndCustAccessorialCharge_RecordID '
10033 END
10034
10035 IF EXISTS(SELECT 1 FROM #Column AS C WHERE C.CName ='TotalCharges')
10036 BEGIN
10037 -- create clusteredINDEX TotalCharge_RecordID ON #TotalCharge(TotalCharge_RecordID)
10038 SET @sql = @sql + ' LEFT OUTER JOIN #TotalCharge AS TC ON RecordID = TotalCharge_RecordID '
10039 END
10040
10041 IF EXISTS(SELECT 1 FROM #Column AS C WHERE C.CName ='EndCustTotalCharges')
10042 BEGIN
10043 -- create clusteredINDEX EndCustTotalCharges_RecordID ON #EndCustTotalCharges(EndCustTotalCharges_RecordID)
10044 SET @sql = @sql + ' LEFT OUTER JOIN #EndCustTotalCharges ON RecordID = EndCustTotalCharges_RecordID '
10045 END
10046 IF EXISTS(SELECT 1 FROM #Column AS C WHERE C.CName ='SourceCurrencyCode')
10047 BEGIN
10048 -- create clusteredINDEX SourceCurrencyCode_RecordID ON #SourceCurrencyCode(SourceCurrencyCode_RecordID)
10049 SET @sql = @sql + ' LEFT OUTER JOIN #SourceCurrencyCode ON RecordID = SourceCurrencyCode_RecordID '
10050 END
10051
10052 IF EXISTS(SELECT 1 FROM #Column AS C WHERE C.CName ='OrderedSpace')
10053 BEGIN
10054 -- create clusteredINDEX SourceCurrencyCode_RecordID ON #SourceCurrencyCode(SourceCurrencyCode_RecordID)
10055 SET @sql = @sql + ' LEFT OUTER JOIN #OrderedSpace ON RecordID = OrderedSpace_RecordID '
10056 END
10057
10058
10059 SET @sql = @sql + ' OPTION(HASH JOIN)'
10060
10061 -- We had an issue when in Express for same Pick and drop there were 2 different orders created.
10062 -- That caused this report to show duplicate lines for Per Origin\Destination report. Adding
10063 -- DISTINCT resolves this problem.
10064 SET @sqlDistinct=''
10065 IF (@SummarizeShipment=0 OR @SummarizeOcean=1) AND @ReportLevel < 16 -- reportlevel flags enums combined for shipment level reports will always be less than 16 (old check was for 1)
10066 BEGIN
10067 SET @sqlDistinct='DISTINCT'
10068 END
10069
10070 -- SET @sql = 'SELECT RecordID' + CASE WHEN NULLIF(@SelectClause, '') IS NOT NULL THEN ',' END + @sql + ' order by recordid '
10071 /*-- SET @SelectClause = 'InvoiceDate,InvoiceNum,CHRListBillNum,ContainerNumber,DeliveryCarrierName,OrigName,OrigAddress1,OrigAddress2,OrigCity,OrigState,OrigZip,OrigLocationID,DestName,DestAddress1,DestAddress2,DestCity,DestState,DestZip,DestLocationI
10072
10073
10074D,
10075CustomerName,ShipperName,ConsigneeName,VendorName,ImporterOfRecord,Buyer,OrigTerminalName,OrigTerminalCity,OrigRampName,OrigRampCity,LoadingPort,LoadingPortCountry,DischargePort,DischargePortCountry,DestRampName,DestRampCity,DestTerminalName,DestTerminalC
10076
10077
10078
10079ity,PoolpointName,PoolpointCity,PoolpointState,CrossDockName,CrossDockCity,CrossDockState,EarliestReqPickupDate,EarliestReqPickupTime,LatestReqPickupDate,LatestReqPickupTime,EarliestSchedPickupDate,EarliestSchedPickupTime,LatestSchedPickupDate,LatestSched
10080
10081
10082
10083PickupTime,EarliestActualPickupDate,EarliestActualPickupTime,LatestActualPickupDate,LatestActualPickupTime,EstimatedPickupDate,ShipperDropTrailerArrivalDate,ShipperDropTrailerArrivalTime,EarliestReqDeliveryDate,EarliestReqDeliveryTime,LatestReqDeliveryDat
10084
10085
10086
10087e,LatestReqDeliveryTime,EarliestSchedDeliveryDate,EarliestSchedDeliveryTime,LatestSchedDeliveryDate,LatestSchedDeliveryTime,EarliestActualDeliveryDate,EarliestActualDeliveryTime,LatestActualDeliveryDate,LatestActualDeliveryTime,EstimatedDeliveryDate,Consi
10088
10089
10090
10091gneeDropTrailerArrivalDate,ConsigneeDropTrailerArrivalTime,PoolpointSchedArrivalDate,PoolpointSchedArrivalTime,PoolpointSchedDepartDate,PoolpointSchedDepartTime,PoolpointActualArrivalDate,PoolpointActualArrivalTime,PoolpointActualDepartDate,PoolpointActua
10092
10093
10094
10095lDepartTime,CrossDockArrivalDate,CrossDockArrivalTime,CrossDockSchedDepartDate,CrossDockSchedDepartTime,CrossDockActualDepartDate,CrossDockActualDepartTime,OrigTerminalETADate,OrigTerminalArrivalDate,OrigTerminalArrivalTime,OrigTerminalDepartDate,OrigTerm
10096
10097
10098
10099inalDepartTime,OrigRampCutOffDate,OrigRampCutOffTime,OrigRampArrivalDate,OrigRampArrivalTime,OrigRampRampedDate,OrigRampRampedTime,PortCutoffDate,OriginalPortETDDate,PortETDDate,OriginalPortETADate,PortETADate,ActualPortArrivalDate,ActualPortDepartDate,De
10100
10101
10102
10103stRampArrivalDate,DestRampArrivalTime,DestRampDeRampedDate,DestRampDeRampedTime,RailETADate,DestTerminalETADate,DestTerminalArrivalDate,DestTerminalArrivalTime,DestTerminalDepartDate,DestTerminalDepartTime,IMDLPromiseDate,EnterDate,OceanAirProofOfDelivery
10104
10105
10106
10107Date,CloseDate,DocumentTrackingDate,DeliveryOrderCreatedDate,TruckloadActivityDate,CHRNumber,SummaryActualQuantity,SummaryExpectedQuantity,SummaryDriverHeavyWeightTix,SummaryCommodity,SummaryActualPallets,SummaryExpectedPallets,SummaryDriverLightWeightTix
10108
10109
10110
10111,SummaryDescription,SummaryActualWeight,SummaryExpectedMinWeight,SummaryHazardous,SummaryPalletSpaces,SummaryExpectedMaxWeight,SummaryVolume,FreightCharge,AccessorialOtherCharge,TotalCharges,BaselineCharge,EndCustFreightCharge,EndCustAccessorialCharge,End
10112
10113
10114
10115CustTotalCharges,NonConsolidationCharge,CHRStatus,Mode,Comment,Expedited,ExpeditedReason,SourceCurrencyCode,InboundStatus,OrderedBy,EnteredBy,NonComplianceCode,NonComplianceCodeReason,Invoiced,LastInvoiceDate,FinancialCondition,LastEvent,OrigSpecialInstru
10116
10117
10118ctions,DestSpecialInstru
10119ctions,Voyage,Vessel,ContractNum,BookingNum,BookingDate,MasterLinehaulName,CarrierName,LTLSCAC,EquipmentType,ContainerType,TractorNum,TrailerNum,TenderedToCarrierName,TrailerSize,ITNum,SSLReleaseDate,EntryLocation,OGAReleaseDate,ReceiptDocsDate,ITLocation
10120
10121
10122
10123,EntryDate,ExamRequiredDate,TenderedToCarrierDate,FDAEntry,ITDate,EntryNum,CustomsHoldDate,TurnedOverDate,FDAReqDate,ReleaseDate,BrokerName,OGAHoldDate,Notes,FDASubmitDate'*/
10124 SET @sql = CASE
10125 WHEN NULLIF(@SelectClause, '') IS NOT NULL THEN 'SELECT ' + @sqlDistinct + ' RecordID,ShipmentMode,LogisticFlg,' + @SelectClause + @sql --+ ' order by recordid '
10126 ELSE 'SELECT ' + @sqlDistinct + ' RecordID,ShipmentMode,LogisticFlg,' + @sql --+ ' order by recordid '
10127 END
10128
10129-- SET @SQL = 'SELECT RECORDID ' + @SQL + ' GROUP BY RECORDID HAVING COUNT(1) > 1 ORDER BY RECORDID '
10130
10131 /********************************************************************************************************/
10132 /******************** EXECUTE @SQL **********************************************************************/
10133 /********************************************************************************************************/
10134 --select @sql
10135
10136 --PRINT 'About to Execute Result Query'
10137 EXECUTE sp_executesql @sql
10138 --PRINT 'Done With Execute Result Query'
10139
10140-- SELECT * FROM #Payer
10141-- SELECT * FROM #SpecialInstructions
10142-- SELECT * FROM #CustomerLocation
10143-- SELECT * FROM #MISC
10144-- --SELECT * FROM #POD
10145-- SELECT * FROM #MiscDate
10146-- SELECT * FROM #InterLocation
10147-- SELECT * FROM #FUDate
10148-- SELECT * FROM #LFUDate
10149-- SELECT * FROM #Invoice
10150--SELECT * FROM #Item
10151-- SELECT * FROM #ItemSummary
10152-- SELECT * FROM #ItemSummaryText
10153-- SELECT * FROM #Ref
10154-- SELECT * FROM #ItemRef
10155-- SELECT * FROM #AccessorialChargeDescription
10156-- SELECT * FROM #FreightCharge
10157-- SELECT * FROM #AccessorialOtherCharge
10158-- SELECT * FROM #TotalCharge
10159-- SELECT * FROM #EndCustFreightCharge
10160-- SELECT * FROM #EndCustAccessorialCharge
10161-- SELECT * FROM #EndCustTotalCharges
10162-- SELECT * FROM #SourceCurrencyCode
10163-- SELECT * FROM #Comment
10164-- SELECT * FROM #COService
10165-- SELECT * FROM #LastInvoice
10166-- SELECT * FROM #Alert
10167-- --SELECT * FROM #ClosedAlert
10168-- SELECT * FROM #LastEvent
10169-- SELECT * FROM #SPOrder
10170-- SELECT * FROM #SPOrderIntl
10171-- SELECT * FROM #SPOrderOther
10172-- SELECT * FROM #SCAC
10173-- SELECT * FROM #Customs
10174-- SELECT * FROM #PoolCrossLocation
10175-- SELECT * FROM #PoolCrossLocationDate
10176--SELECT * FROM #POItems
10177-- SELECT * FROm #POVendor
10178--SELECT * FROM #Row
10179-- select * from #POItemLocation
10180-- select * from #POItemReference
10181-- --SELECT * FROM #Column
10182--select * from #POEndCustomer
10183--select * from #POBuyer
10184
10185SET NOCOUNT OFF
10186END