Reduce SQL query execution time - sql-server

I have a situation where our web application generates a Crystal Report based on the query result which takes almost 1 hr to execute.
I know this is crazy but, can anyone suggest any optimization or changes in the following giant query.
Thanks.
Note: I have shorten some of the similar queries.
CREATE procedure [dbo].[sp_ExportRevenueMenifest_27FEB]
(#vessel varchar(10), #voyage varchar(10),
#call varchar(10), #GLC varchar(10),
#Port varchar(10), #str varchar(200))
AS
create table #OCF (PortCode varchar(10),
PortName varchar(40),
BLNumber varchar(20), RS decimal(18,4),
RS1 decimal(18,4), Consignee varchar(500),
NoPackages varchar(50), Vessel varchar(10),
Vayage varchar(10), Call char(2),
Vessel_Name varchar(50),
Sailed_Date varchar(20), ExRate decimal(8,4)
)
insert into #OCF
SELECT a.PortofDischarge, Port_Master.Port_Name, a.BLNumber, SUM(B.PrepaidAmtUSD) AS PrepaidAmtUSD,SUM(B.COLLECTAmtUSD) AS COLLECTAmtUSD, a.Consignee, a.NoPackages, a.Vessel,
a.Voyage, a.Call, Vessel_Master.Vessel_Name, ExportVoyage_Master.Sailed_Date, a.ExchangeRate
FROM BLMaster a INNER JOIN
BL_ChargesDetails B ON a.BLID = B.BLID INNER JOIN
ExportVoyage_Master ON a.Vessel = ExportVoyage_Master.Vessel_Code AND a.Voyage = ExportVoyage_Master.Voyage_Code AND
a.Port = ExportVoyage_Master.Port AND a.Call = ExportVoyage_Master.Call INNER JOIN
Vessel_Master ON ExportVoyage_Master.Vessel_Code = Vessel_Master.Vessel_Code INNER JOIN
Port_Master ON a.PortofDischarge = Port_Master.Port_Code
WHERE (a.ImportExport = 2) AND (B.ConfigCode = 'OCF')
GROUP BY Port_Master.Port_Name, a.BLNumber, a.Consignee, a.NoPackages, a.Vessel, a.Voyage, a.Call, Vessel_Master.Vessel_Name,
ExportVoyage_Master.Sailed_Date, a.PortofDischarge, a.ExchangeRate, B.ConfigCode
create table #DDC (PortCode varchar(10), PortName varchar(40),BLNumber varchar(20), RS decimal(18,4),RS1 decimal(18,4),Consignee varchar(500),NoPackages varchar(50),Vessel varchar(10),Vayage varchar(10),Call char(2),Vessel_Name varchar(50),Sailed_Date varchar(20),ExRate decimal(8,4))
insert into #DDC
SELECT a.PortofDischarge, Port_Master.Port_Name, a.BLNumber, SUM(B.PrepaidAmtUSD) AS PrepaidAmtUSD,SUM(B.COLLECTAmtUSD) AS COLLECTAmtUSD, a.Consignee, a.NoPackages, a.Vessel,
a.Voyage, a.Call, Vessel_Master.Vessel_Name, ExportVoyage_Master.Sailed_Date, a.ExchangeRate
FROM BLMaster a INNER JOIN
BL_ChargesDetails B ON a.BLID = B.BLID INNER JOIN
ExportVoyage_Master ON a.Vessel = ExportVoyage_Master.Vessel_Code AND a.Voyage = ExportVoyage_Master.Voyage_Code AND
a.Port = ExportVoyage_Master.Port AND a.Call = ExportVoyage_Master.Call INNER JOIN
Vessel_Master ON ExportVoyage_Master.Vessel_Code = Vessel_Master.Vessel_Code INNER JOIN
Port_Master ON a.PortofDischarge = Port_Master.Port_Code
WHERE (a.ImportExport = 2) AND (B.ConfigCode = 'DDC')
GROUP BY Port_Master.Port_Name, a.BLNumber, a.Consignee, a.NoPackages, a.Vessel, a.Voyage, a.Call, Vessel_Master.Vessel_Name,
ExportVoyage_Master.Sailed_Date, a.PortofDischarge, a.ExchangeRate, B.ConfigCode
create table #FUM (PortCode varchar(10), PortName varchar(40),BLNumber varchar(20), RS decimal(18,4),RS1 decimal(18,4),Consignee varchar(500),NoPackages varchar(50),Vessel varchar(10),Vayage varchar(10),Call char(2),Vessel_Name varchar(50),Sailed_Date varchar(20),ExRate decimal(8,4))
insert into #FUM
SELECT a.PortofDischarge, ....., a.Vessel,
a.Voyage, a.Call, Vessel_Master.Vessel_Name, ExportVoyage_Master.Sailed_Date, a.ExchangeRate
FROM BLMaster a INNER JOIN
BL_ChargesDetails B ON a.BLID = B.BLID INNER JOIN
....INNER JOIN
Port_Master ON a.PortofDischarge = Port_Master.Port_Code
WHERE (a.ImportExport = 2) AND (B.ConfigCode = 'FUM')
GROUP BY Port_Master.Port_Name,.... B.ConfigCode
create table #PSS (PortCode varchar(10), PortName varchar(40),BLNumber varchar(20), RS decimal(18,4),RS1 decimal(18,4),Consignee varchar(500),NoPackages varchar(50),Vessel varchar(10),Vayage varchar(10),Call char(2),Vessel_Name varchar(50),Sailed_Date varchar(20),ExRate decimal(8,4))
insert into #PSS
SELECT a.PortofDischarge, .... a.ExchangeRate
FROM BLMaster a INNER JOIN
BL_ChargesDetails B ON a.BLID = B.BLID INNER JOIN
ExportVoyage_Master ON a.Vessel = ExportVoyage_Master.Vessel_Code AND a.Voyage = ExportVoyage_Master.Voyage_Code AND
a.Port = ExportVoyage_Master.Port AND a.Call = ExportVoyage_Master.Call INNER JOIN
Vessel_Master ON ExportVoyage_Master.Vessel_Code = Vessel_Master.Vessel_Code INNER JOIN
Port_Master ON a.PortofDischarge = Port_Master.Port_Code
WHERE (a.ImportExport = 2) AND (B.ConfigCode = 'PSS')
GROUP BY Port_Master.Port_Name, ....., B.ConfigCode
create table #BAF (PortCode varchar(10), PortName varchar(40),BLNumber varchar(20), RS decimal(18,4),RS1 decimal(18,4),Consignee varchar(500),NoPackages varchar(50),Vessel varchar(10),Vayage varchar(10),Call char(2),Vessel_Name varchar(50),Sailed_Date varchar(20),ExRate decimal(8,4))
insert into #BAF
SELECT a.PortofDischarge, .... a.Vessel,
a.Voyage, a.Call, Vessel_Master.Vessel_Name, ExportVoyage_Master.Sailed_Date, a.ExchangeRate
FROM BLMaster a INNER JOIN
BL_ChargesDetails B ON a.BLID = B.BLID INNER JOIN
...... ON a.PortofDischarge = Port_Master.Port_Code
WHERE (a.ImportExport = 2) AND (B.ConfigCode = 'BAF')
GROUP BY Port_Master.Port_Name, ..... B.ConfigCode
create table #HD (PortCode varchar(10), PortName varchar(40),BLNumber varchar(20), RS decimal(18,4),RS1 decimal(18,4),Consignee varchar(500),NoPackages varchar(50),Vessel varchar(10),Vayage varchar(10),Call char(2),Vessel_Name varchar(50),Sailed_Date varchar(20),ExRate decimal(8,4))
insert into #HD
SELECT a.PortofDischarge, ..... a.Vessel,
a.Voyage, a.Call, Vessel_Master.Vessel_Name, ExportVoyage_Master.Sailed_Date, a.ExchangeRate
FROM BLMaster a INNER JOIN
BL_ChargesDetails B ON a.BLID = B.BLID INNER JOIN
ExportVoyage_Master ON a.Vessel = ExportVoyage_Master.Vessel_Code AND a.Voyage = ExportVoyage_Master.Voyage_Code AND
...... ON a.PortofDischarge = Port_Master.Port_Code
WHERE (a.ImportExport = 2) AND (B.ConfigCode = 'HD')
GROUP BY Port_Master.Port_Name, ..... B.ConfigCode
create table #WRS (PortCode varchar(10), PortName varchar(40),BLNumber varchar(20), RS decimal(18,4),RS1 decimal(18,4),Consignee varchar(500),NoPackages varchar(50),Vessel varchar(10),Vayage varchar(10),Call char(2),Vessel_Name varchar(50),Sailed_Date varchar(20),ExRate decimal(8,4))
insert into #WRS
SELECT a.PortofDischarge, Port_Master.Port_Name, a.BLNumber, SUM(B.PrepaidAmtUSD) AS PrepaidAmtUSD,SUM(B.COLLECTAmtUSD) AS COLLECTAmtUSD, a.Consignee, a.NoPackages, a.Vessel,
a.Voyage, a.Call, Vessel_Master.Vessel_Name, ExportVoyage_Master.Sailed_Date, a.ExchangeRate
FROM BLMaster a INNER JOIN
BL_ChargesDetails B ON a.BLID = B.BLID INNER JOIN
ExportVoyage_Master ON a.Vessel = ExportVoyage_Master.Vessel_Code AND a.Voyage = ExportVoyage_Master.Voyage_Code AND
a.Port = ExportVoyage_Master.Port AND a.Call = ExportVoyage_Master.Call INNER JOIN
Vessel_Master ON ExportVoyage_Master.Vessel_Code = Vessel_Master.Vessel_Code INNER JOIN
Port_Master ON a.PortofDischarge = Port_Master.Port_Code
WHERE (a.ImportExport = 2) AND (B.ConfigCode = 'WRS')
GROUP BY Port_Master.Port_Name, a.BLNumber, a.Consignee, a.NoPackages, a.Vessel, a.Voyage, a.Call, Vessel_Master.Vessel_Name,
ExportVoyage_Master.Sailed_Date, a.PortofDischarge, a.ExchangeRate, B.ConfigCode
create table #DIV (PortCode varchar(10), PortName varchar(40),BLNumber varchar(20), RS decimal(18,4),RS1 decimal(18,4),Consignee varchar(500),NoPackages varchar(50),Vessel varchar(10),Vayage varchar(10),Call char(2),Vessel_Name varchar(50),Sailed_Date varchar(20),ExRate decimal(8,4))
insert into #DIV
SELECT a.PortofDischarge, Port_Master.Port_Name, a.BLNumber, SUM(B.PrepaidAmtUSD) AS PrepaidAmtUSD,SUM(B.COLLECTAmtUSD) AS COLLECTAmtUSD, a.Consignee, a.NoPackages, a.Vessel,
a.Voyage, a.Call, Vessel_Master.Vessel_Name, ExportVoyage_Master.Sailed_Date, a.ExchangeRate
FROM BLMaster a INNER JOIN
BL_ChargesDetails B ON a.BLID = B.BLID INNER JOIN
ExportVoyage_Master ON a.Vessel = ExportVoyage_Master.Vessel_Code AND a.Voyage = ExportVoyage_Master.Voyage_Code AND
a.Port = ExportVoyage_Master.Port AND a.Call = ExportVoyage_Master.Call INNER JOIN
Vessel_Master ON ExportVoyage_Master.Vessel_Code = Vessel_Master.Vessel_Code INNER JOIN
Port_Master ON a.PortofDischarge = Port_Master.Port_Code
WHERE (a.ImportExport = 2) AND (B.ConfigCode = 'DIV')
GROUP BY Port_Master.Port_Name, a.BLNumber, a.Consignee, a.NoPackages, a.Vessel, a.Voyage, a.Call, Vessel_Master.Vessel_Name,
ExportVoyage_Master.Sailed_Date, a.PortofDischarge, a.ExchangeRate, B.ConfigCode
create table #PAN (PortCode varchar(10), PortName varchar(40),BLNumber varchar(20), RS decimal(18,4),RS1 decimal(18,4),Consignee varchar(500),NoPackages varchar(50),Vessel varchar(10),Vayage varchar(10),Call char(2),Vessel_Name varchar(50),Sailed_Date varchar(20),ExRate decimal(8,4))
insert into #PAN
SELECT a.PortofDischarge, Port_Master.Port_Name, a.BLNumber, SUM(B.PrepaidAmtUSD) AS PrepaidAmtUSD,SUM(B.COLLECTAmtUSD) AS COLLECTAmtUSD, a.Consignee, a.NoPackages, a.Vessel,
a.Voyage, a.Call, Vessel_Master.Vessel_Name, ExportVoyage_Master.Sailed_Date, a.ExchangeRate
FROM BLMaster a INNER JOIN
BL_ChargesDetails B ON a.BLID = B.BLID INNER JOIN
ExportVoyage_Master ON a.Vessel = ExportVoyage_Master.Vessel_Code AND a.Voyage = ExportVoyage_Master.Voyage_Code AND
a.Port = ExportVoyage_Master.Port AND a.Call = ExportVoyage_Master.Call INNER JOIN
Vessel_Master ON ExportVoyage_Master.Vessel_Code = Vessel_Master.Vessel_Code INNER JOIN
Port_Master ON a.PortofDischarge = Port_Master.Port_Code
WHERE (a.ImportExport = 2) AND (B.ConfigCode = 'PAN')
GROUP BY Port_Master.Port_Name, a.BLNumber, a.Consignee, a.NoPackages, a.Vessel, a.Voyage, a.Call, Vessel_Master.Vessel_Name,
ExportVoyage_Master.Sailed_Date, a.PortofDischarge, a.ExchangeRate, B.ConfigCode
create table #CAF (PortCode varchar(10), PortName varchar(40),BLNumber varchar(20), RS decimal(18,4),RS1 decimal(18,4),Consignee varchar(500),NoPackages varchar(50),Vessel varchar(10),Vayage varchar(10),Call char(2),Vessel_Name varchar(50),Sailed_Date varchar(20),ExRate decimal(8,4))
insert into #CAF
SELECT a.PortofDischarge, Port_Master.Port_Name, a.BLNumber, SUM(B.PrepaidAmtUSD) AS PrepaidAmtUSD,SUM(B.COLLECTAmtUSD) AS COLLECTAmtUSD, a.Consignee, a.NoPackages, a.Vessel,
a.Voyage, a.Call, Vessel_Master.Vessel_Name, ExportVoyage_Master.Sailed_Date, a.ExchangeRate
FROM BLMaster a INNER JOIN
BL_ChargesDetails B ON a.BLID = B.BLID INNER JOIN
ExportVoyage_Master ON a.Vessel = ExportVoyage_Master.Vessel_Code AND a.Voyage = ExportVoyage_Master.Voyage_Code AND
a.Port = ExportVoyage_Master.Port AND a.Call = ExportVoyage_Master.Call INNER JOIN
Vessel_Master ON ExportVoyage_Master.Vessel_Code = Vessel_Master.Vessel_Code INNER JOIN
Port_Master ON a.PortofDischarge = Port_Master.Port_Code
WHERE (a.ImportExport = 2) AND (B.ConfigCode = 'CAF')
GROUP BY Port_Master.Port_Name, a.BLNumber, a.Consignee, a.NoPackages, a.Vessel, a.Voyage, a.Call, Vessel_Master.Vessel_Name,
ExportVoyage_Master.Sailed_Date, a.PortofDischarge, a.ExchangeRate, B.ConfigCode
create table #CDR (PortCode varchar(10), PortName varchar(40),BLNumber varchar(20), RS decimal(18,4),RS1 decimal(18,4),Consignee varchar(500),NoPackages varchar(50),Vessel varchar(10),Vayage varchar(10),Call char(2),Vessel_Name varchar(50),Sailed_Date varchar(20),ExRate decimal(8,4))
insert into #CDR
SELECT a.PortofDischarge, Port_Master.Port_Name, a.BLNumber, SUM(B.PrepaidAmtUSD) AS PrepaidAmtUSD,SUM(B.COLLECTAmtUSD) AS COLLECTAmtUSD, a.Consignee, a.NoPackages, a.Vessel,
a.Voyage, a.Call, Vessel_Master.Vessel_Name, ExportVoyage_Master.Sailed_Date, a.ExchangeRate
FROM BLMaster a INNER JOIN
..... ON a.PortofDischarge = Port_Master.Port_Code
WHERE (a.ImportExport = 2) AND (B.ConfigCode = 'CDR')
GROUP BY Port_Master.Port_Name, .... B.ConfigCode
create table #THC (PortCode varchar(10), PortName varchar(40),BLNumber varchar(20), RS decimal(18),RS1 decimal(18),Consignee varchar(500),NoPackages varchar(50),Vessel varchar(10),Vayage varchar(10),Call char(2),Vessel_Name varchar(50),Sailed_Date varchar(20),ExRate decimal(8,4))
insert into #THC
SELECT a.PortofDischarge, ......, a.Vessel,
a.Voyage, a.Call, Vessel_Master.Vessel_Name, ExportVoyage_Master.Sailed_Date, a.ExchangeRate
FROM BLMaster a INNER JOIN
BL_ChargesDetails B ON a.BLID = B.BLID INNER JOIN
......
WHERE (a.ImportExport = 2) AND (B.ConfigCode = 'THC')
GROUP BY Port_Master.Port_Name, a.BLNumber, a.Consignee, a.NoPackages, a.Vessel, a.Voyage, a.Call, Vessel_Master.Vessel_Name,
ExportVoyage_Master.Sailed_Date, a.PortofDischarge, a.ExchangeRate, B.ConfigCode
create table #INL (PortCode varchar(10),....,ExRate decimal(8,4))
insert into #INL
SELECT a.PortofDischarge, Port_Master.Port_Name, a.BLNumber, SUM(B.PrepaidAmtRupee) AS PrepaidAmtRupee,SUM(B.CollectAmtRupee) AS collectAmtRupee, a.Consignee, a.NoPackages, a.Vessel,
a.Voyage, a.Call, Vessel_Master.Vessel_Name, ExportVoyage_Master.Sailed_Date, a.ExchangeRate
FROM BLMaster a INNER JOIN
......
WHERE (a.ImportExport = 2) AND (B.ConfigCode = 'INL')
GROUP BY Port_Master.Port_Name, ......, B.ConfigCode
create table #ARB (PortCode varchar(10), PortName varchar(40),BLNumber varchar(20), RS decimal(18,4),RS1 decimal(18,4),Consignee varchar(500),NoPackages varchar(50),Vessel varchar(10),Vayage varchar(10),Call char(2),Vessel_Name varchar(50),Sailed_Date varchar(20),ExRate decimal(8,4))
insert into #ARB
SELECT a.PortofDischarge, Port_Master.Port_Name, a.BLNumber, SUM(B.PrepaidAmtRupee) AS PrepaidAmtRupee,SUM(B.CollectAmtRupee) AS collectAmtRupee, a.Consignee, a.NoPackages, a.Vessel,
a.Voyage, a.Call, Vessel_Master.Vessel_Name, ExportVoyage_Master.Sailed_Date, a.ExchangeRate
FROM BLMaster a INNER JOIN
BL_ChargesDetails B ON a.BLID = B.BLID INNER JOIN
ExportVoyage_Master ON a.Vessel = ExportVoyage_Master.Vessel_Code AND a.Voyage = ExportVoyage_Master.Voyage_Code AND
a.Port = ExportVoyage_Master.Port AND a.Call = ExportVoyage_Master.Call INNER JOIN
Vessel_Master ON ExportVoyage_Master.Vessel_Code = Vessel_Master.Vessel_Code INNER JOIN
Port_Master ON a.PortofDischarge = Port_Master.Port_Code
WHERE (a.ImportExport = 2) AND (B.ConfigCode = 'ARB')
GROUP BY Port_Master.Port_Name, a.BLNumber, a.Consignee, a.NoPackages, a.Vessel, a.Voyage, a.Call, Vessel_Master.Vessel_Name,
ExportVoyage_Master.Sailed_Date, a.PortofDischarge, a.ExchangeRate, B.ConfigCode
create table #DOC (PortCode varchar(10), PortName varchar(40),BLNumber varchar(20), RS decimal(18,4),RS1 decimal(18,4),Consignee varchar(500),NoPackages varchar(50),Vessel varchar(10),Vayage varchar(10),Call char(2),Vessel_Name varchar(50),Sailed_Date varchar(20),ExRate decimal(8,4))
insert into #DOC
SELECT a.PortofDischarge, .... a.Vessel,
a.Voyage, a.Call, Vessel_Master.Vessel_Name, ExportVoyage_Master.Sailed_Date, a.ExchangeRate
FROM BLMaster a INNER JOIN
BL_ChargesDetails B ON a.BLID = B.BLID INNER JOIN
ExportVoyage_Master ON a.Vessel = ExportVoyage_Master.Vessel_Code AND a.Voyage = ExportVoyage_Master.Voyage_Code AND
.... ON a.PortofDischarge = Port_Master.Port_Code
WHERE (a.ImportExport = 2) AND (B.ConfigCode = 'DOC')
GROUP BY Port_Master.Port_Name, ...., B.ConfigCode
create table #THCUSD (PortCode varchar(10), PortName varchar(40),BLNumber varchar(20), RS decimal(18,4),RS1 decimal(18,4),Consignee varchar(500),NoPackages varchar(50),Vessel varchar(10),Vayage varchar(10),Call char(2),Vessel_Name varchar(50),Sailed_Date varchar(20),ExRate decimal(8,4))
insert into #THCUSD
SELECT a.PortofDischarge, .... a.Vessel,
a.Voyage, a.Call, Vessel_Master.Vessel_Name, ExportVoyage_Master.Sailed_Date, a.ExchangeRate
FROM BLMaster a INNER JOIN
BL_ChargesDetails B ON a.BLID = B.BLID INNER JOIN
ExportVoyage_Master ON a.Vessel = ExportVoyage_Master.Vessel_Code AND a.Voyage = ExportVoyage_Master.Voyage_Code AND
.... ON a.PortofDischarge = Port_Master.Port_Code
WHERE (a.ImportExport = 2) AND (b.ConfigCode='THC')
GROUP BY Port_Master.Port_Name,...., a.ExchangeRate
create table #INLUSD (PortCode varchar(10), PortName varchar(40),BLNumber varchar(20), RS decimal(18,4),RS1 decimal(18,4),Consignee varchar(500),NoPackages varchar(50),Vessel varchar(10),Vayage varchar(10),Call char(2),Vessel_Name varchar(50),Sailed_Date varchar(20),ExRate decimal(8,4))
insert into #INLUSD
SELECT a.PortofDischarge, .... a.Vessel,
a.Voyage, a.Call, Vessel_Master.Vessel_Name, ExportVoyage_Master.Sailed_Date, a.ExchangeRate
FROM BLMaster a INNER JOIN
BL_ChargesDetails B ON a.BLID = B.BLID INNER JOIN
ExportVoyage_Master ON a.Vessel = ExportVoyage_Master.Vessel_Code AND a.Voyage = ExportVoyage_Master.Voyage_Code AND
.....ON a.PortofDischarge = Port_Master.Port_Code
WHERE (a.ImportExport = 2) AND (b.ConfigCode='INL')
GROUP BY Port_Master.Port_Name,.... a.ExchangeRate
create table #ARBUSD (PortCode varchar(10), PortName varchar(40),BLNumber varchar(20), RS decimal(18,4),RS1 decimal(18,4),Consignee varchar(500),NoPackages varchar(50),Vessel varchar(10),Vayage varchar(10),Call char(2),Vessel_Name varchar(50),Sailed_Date varchar(20),ExRate decimal(8,4))
insert into #ARBUSD
SELECT a.PortofDischarge, ....., a.Vessel,
a.Voyage, a.Call, Vessel_Master.Vessel_Name, ExportVoyage_Master.Sailed_Date, a.ExchangeRate
FROM BLMaster a INNER JOIN
.....
Port_Master ON a.PortofDischarge = Port_Master.Port_Code
WHERE (a.ImportExport = 2) AND (b.ConfigCode='ARB')
GROUP BY Port_Master.Port_Name,.... a.ExchangeRate
create table #OTH (PortCode varchar(10), PortName varchar(40),BLNumber varchar(20), RS decimal(18,4),RS1 decimal(18,4),Consignee varchar(500),NoPackages varchar(50),Vessel varchar(10),Vayage varchar(10),Call char(2),Vessel_Name varchar(50),Sailed_Date varchar(20),ExRate decimal(8,4))
insert into #OTH
SELECT a.PortofDischarge, Port_Master.Port_Name, a.BLNumber, SUM(B.PrepaidAmtUSD) AS PrepaidAmtUSD,SUM(B.COLLECTAmtUSD) AS COLLECTAmtUSD, a.Consignee, a.NoPackages, a.Vessel,
a.Voyage, a.Call, Vessel_Master.Vessel_Name, ExportVoyage_Master.Sailed_Date, a.ExchangeRate
FROM BLMaster a INNER JOIN
BL_ChargesDetails B ON a.BLID = B.BLID INNER JOIN
ExportVoyage_Master ON a.Vessel = ExportVoyage_Master.Vessel_Code AND a.Voyage = ExportVoyage_Master.Voyage_Code AND
a.Port = ExportVoyage_Master.Port AND a.Call = ExportVoyage_Master.Call INNER JOIN
Vessel_Master ON ExportVoyage_Master.Vessel_Code = Vessel_Master.Vessel_Code INNER JOIN
Port_Master ON a.PortofDischarge = Port_Master.Port_Code
WHERE (a.ImportExport = 2) AND b.ConfigCode NOT IN('OCF','FUM','BAF','YAS','CAF','HD','DIV','PSS','CAF','PSS','PAN','WRS','CDR','THC','INL','DDC','ARB','DOC','STX')
GROUP BY Port_Master.Port_Name, a.BLNumber, a.Consignee, a.NoPackages, a.Vessel, a.Voyage, a.Call, Vessel_Master.Vessel_Name,
ExportVoyage_Master.Sailed_Date, a.PortofDischarge, a.ExchangeRate
DECLARE #Query varchar(8000)
SET #Query = ''
SELECT #Query ='SELECT Port_Master.Port_Name,Vessel_Master.Vessel_Name, Vessel_Master.Vessel_Code, ExportVoyage_Master.Voyage_Code, ExportVoyage_Master.Sailed_Date,
Vessel_Master.Nationality, ExportVoyage_Master.Master, a.Portofloading,a.PortofDischarge,a.FinalDestination, ExportVoyage_Master.Call,ExportVoyage_Master.Berth_Date,a.BLNumber,a.Shipper, a.Consignee,a.port,
a.MarksNo, a.GoodsDescription, a.NoPackages, BL_ClubbedContainer.ContainerNo,
BL_ClubbedContainer.TypeSize, A.ExchangeRate, a.BrokerCode,
isnull(OC.RS,0)OCF,isnull(FU.RS,0)FUM,isnull(BA.RS,0)BAF,isnull(CA.RS,0)CAF,isnull(HD.RS,0)HD,isnull(DI.RS,0)DIV,isnull(PS.RS,0)PSS,isnull(PA.RS,0)PAN,isnull(WR.RS,0)WRS,isnull(CD.RS,0)CDR,isnull(TH.RS,0)THC,isnull(DD.RS,0)DDC,isnull(INL.RS,0)INL,isnull(AR.RS,0)ARB,isnull(DO.RS,0)DOC,isnull(OT.RS,0)OTH,isnull(THUS.RS,0)THCUSD,isnull(INUS.RS,0)INLUSD,isnull(ARUS.RS,0)ARBUSD,isnull(OC.RS1,0)OCF1,isnull(FU.RS1,0)FUM1,isnull(BA.RS1,0)BAF1,isnull(CA.RS1,0)CAF1,isnull(HD.RS1,0)HD1,isnull(DI.RS1,0)DIV1,isnull(PS.RS1,0) PSS1,isnull(PA.RS1,0) PAN1,isnull(WR.RS1,0) WRS1,isnull(CD.RS1,0)CDR1,isnull(TH.RS1,0)THC1,isnull(DD.RS1,0)DDC1,isnull(INL.RS1,0)INL1,isnull(AR.RS1,0)ARB1,isnull(DO.RS1,0) DOC1,isnull(OT.RS1,0)OTH1,isnull(THUS.RS1,0)THCUSD1,isnull(INUS.RS1,0)INLUSD1,isnull(ARUS.RS1,0)ARBUSD1
FROM BLMaster a LEFT OUTER JOIN
BL_ClubbedContainer ON a.BLNumber = BL_ClubbedContainer.BLNumber INNER JOIN
ExportVoyage_Master ON a.Vessel = ExportVoyage_Master.Vessel_Code AND a.Voyage = ExportVoyage_Master.Voyage_Code AND
a.Port = ExportVoyage_Master.Port AND a.Call = ExportVoyage_Master.Call INNER JOIN
Vessel_Master ON ExportVoyage_Master.Vessel_Code = Vessel_Master.Vessel_Code inner join port_master on a.FinalDestination=Port_Master.Port_Code
left outer join #OCF OC on OC.blnumber=a.blnumber
left outer join #DDC DD on DD.blnumber=a.blnumber
left outer join #FUM FU on FU.blnumber=a.blnumber
left outer join #BAF BA on BA.blnumber=a.blnumber
left outer join #HD HD on HD.blnumber=a.blnumber
left outer join #DIV DI on DI.blnumber=a.blnumber
left outer join #WRS WR on WR.blnumber=a.blnumber
left outer join #CAF CA on CA.blnumber=a.blnumber
left outer join #PSS PS on PS.blnumber=a.blnumber
left outer join #PAN PA on PA.blnumber=a.blnumber
left outer join #CDR CD on CD.blnumber=a.blnumber
left outer join #THC TH on TH.blnumber=a.blnumber
left outer join #INL INL on INL.blnumber=a.blnumber
left outer join #ARB AR on AR.blnumber=a.blnumber
left outer join #DOC DO on DO.blnumber=a.blnumber
left outer join #OTH OT on OT.blnumber=a.blnumber
left outer join #THCUSD THUS on THUS.blnumber=a.blnumber
left outer join #INLUSD INUS on INUS.blnumber=a.blnumber
left outer join #ARBUSD ARUS on ARUS.blnumber=a.blnumber
WHERE (a.ImportExport = 2) '+ #str + ' order by a.Portofdischarge,a.blnumber asc'
EXEC (#Query)

From my experience
1) Try to put your parameter into local variable before use.
create procedure [dbo].[usp_test](#Id varchar(20))
as
begin
select * from Test
where Id = #Id
end
to
alter procedure [dbo].[usp_test](#Id varchar(20))
as
begin
declare #local_id varchar(20) = #Id
select * from Test
where Id = #local_id
end
2) Use recompile hint. This will get new query plan which is more suitable for the query based on parameter value.
exec dbo.usp_test 1 with recompile
Ref: https://stackoverflow.com/a/30092833/1554116

Thank you guys for your efforts and time looking into my issue.
The query used to pull all the records from BLMaster without filtering with the parameters passed to the stored procedure.
P.S. Thanks to my vendor.
WHERE (a.ImportExport = 2) AND (B.ConfigCode = 'OCF')
/* Added below two lines to all WHERE clause solved my issue */
AND a.Vessel = #vessel
AND a.Voyage = #voyage
Table BLMaster has around 12lakhs records due to this it was taking so long time.

Related

migrate query sybase to oracle with sign "*="

Hello guys i have this query in sybase with this sign *=, I use in oracle LEFT OUTER JOIN but i dont if right.
Query in sybase:
select
right(( "00" +convert(varchar(2), cta_consol.cod_correo)) , 2) +
right(("000000000" + convert(varchar(11), cta_consol.num_cta_cte)), 9)
from
t_cuenta_consolidada cta_consol,
t_cuenta_corriente ctacte ,
t_empresa empresa,
t_comuna comuna,
t_comuna comuna_CtaCte,
t_ciudad ciudad,
t_ciudad ciudad_CtaCte ,
t_cta_cte_param param
where
empresa.ide = cta_consol.ide_cliente and
empresa.cod_comuna = comuna.codigo and
comuna.cod_ciudad = ciudad.codigo and
ctacte.cod_comuna = comuna_CtaCte.codigo and
comuna_CtaCte.cod_ciudad = ciudad_CtaCte.codigo and
cta_consol.num_cta_cte = ctacte.num_cta_cte and
cta_consol.num_cta_cte *= param.num_cta_cte
cta_consol.num_cta_cte *= param.num_cta_cte
query migrate to oracle:
select
SUBSTR(('00' || CAST(cta_consol.cod_correo AS VARCHAR2(2))),-2) ||
SUBSTR(('000000000' || CAST(cta_consol.num_cta_cte AS VARCHAR2(11))),-9)
from
t_cuenta_consolidada cta_consol
LEFT OUTER JOIN t_cta_cte_param param ON cta_consol.num_cta_cte = param.num_cta_cte,
t_cuenta_corriente ctacte,
t_empresa empresa,
t_comuna comuna,
t_ciudad ciudad
where
empresa.ide = cta_consol.ide_cliente AND
empresa.cod_comuna = comuna.codigo AND
comuna.cod_ciudad = ciudad.codigo AND
ctacte.cod_comuna = comuna.codigo AND
comuna.cod_ciudad = ciudad.codigo AND
cta_consol.num_cta_cte = ctacte.num_cta_cte
LEFT OUTER JOIN t_cta_cte_param param ON cta_consol.num_cta_cte = param.num_cta_cte,
I have compared the amount of registration of each query, and it is not the same
You can mix modern ANSI join syntax with the old proprietary Oracle join syntax, but the order is important.
It's usually easier and less confusing to either do ANSI:
select
SUBSTR(('00' || CAST(cta_consol.cod_correo AS VARCHAR2(2))),-2) ||
SUBSTR(('000000000' || CAST(cta_consol.num_cta_cte AS VARCHAR2(11))),-9)
from
t_cuenta_consolidada cta_consol
LEFT JOIN t_cta_cte_param param ON cta_consol.num_cta_cte = param.num_cta_cte
JOIN t_cuenta_corriente ctacte ON cta_consol.num_cta_cte = ctacte.num_cta_cte
JOIN t_comuna comuna ON ctacte.cod_comuna = comuna.codigo
JOIN t_empresa empresa ON empresa.ide = cta_consol.ide_cliente AND empresa.cod_comuna = comuna.codigo
JOIN t_ciudad ciudad ON comuna.cod_ciudad = ciudad.codigo
WHERE ...
Or old Oracle style:
select
SUBSTR(('00' || CAST(cta_consol.cod_correo AS VARCHAR2(2))),-2) ||
SUBSTR(('000000000' || CAST(cta_consol.num_cta_cte AS VARCHAR2(11))),-9)
from
t_cuenta_consolidada cta_consol,
t_cta_cte_param param,
t_cuenta_corriente ctacte,
t_empresa empresa,
t_comuna comuna,
t_ciudad ciudad
where
empresa.ide = cta_consol.ide_cliente AND
empresa.cod_comuna = comuna.codigo AND
comuna.cod_ciudad = ciudad.codigo AND
ctacte.cod_comuna = comuna.codigo AND
comuna.cod_ciudad = ciudad.codigo AND
cta_consol.num_cta_cte = ctacte.num_cta_cte AND
cta_consol.num_cta_cte = param.num_cta_cte (+)

SQL XML - Create a XML file from SQL Server for an invoice including invoice positions in one XML file

I create my xml file in this way (I do not show all output fields because there are very many fields):
DECLARE #ID_Rechnung int = 8;
WITH XMLNAMESPACES (
'urn:oasis:names:specification:ubl:schema:xsd:CommonExtensionComponents-2' as ext,
'urn:oasis:names:specification:ubl:schema:xsd:CommonBasicComponents-2' as cbc,
'urn:oasis:names:specification:ubl:schema:xsd:CommonAggregateComponents-2' as cac,
'http://uri.etsi.org/01903/v1.3.2#' as xades,
'http://www.w3.org/2001/XMLSchema-instance' as xsi,
'http://www.w3.org/2000/09/xmldsig#' as ds
)
SELECT
#XMLData = xmldat.xmldataCol
FROM
(
SELECT
(
SELECT
-- HIER XML Daten generieren
'' AS 'ext:UBLExtensions',
'' AS 'ext:UBLExtensions/ext:UBLExtension',
'' AS 'ext:UBLExtensions/ext:UBLExtension/ext:ExtensionContent',
'2.1' AS 'cbc:UBLVersionID',
'TR1.2' AS 'cbc:CustomizationID',
'' AS 'cbc:ProfileID',
Rechnungen.Nummer AS 'cbc:ID',
'false' AS 'cbc:CopyIndicator',
'' AS 'cbc:UUID',
CAST(Rechnungen.Datum AS Date) AS 'cbc:IssueDate'
FROM
rechnungen
WHERE
rechnungen.id = #ID_Rechnung
FOR XML PATH(''), ROOT('Invoice')
) AS xmldataCol
This works fine - i get the following XML:
<Invoice xmlns:ds="http://www.w3.org/2000/09/xmldsig#" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xades="http://uri.etsi.org/01903/v1.3.2#" xmlns:cac="urn:oasis:names:specification:ubl:schema:xsd:CommonAggregateComponents-2" xmlns:cbc="urn:oasis:names:specification:ubl:schema:xsd:CommonBasicComponents-2" xmlns:ext="urn:oasis:names:specification:ubl:schema:xsd:CommonExtensionComponents-2">
<ext:UBLExtensions>
<ext:UBLExtension>
<ext:ExtensionContent />
</ext:UBLExtension>
</ext:UBLExtensions>
<cbc:UBLVersionID>2.1</cbc:UBLVersionID>
<cbc:CustomizationID>TR1.2</cbc:CustomizationID>
<cbc:ProfileID />
<cbc:ID>R200001</cbc:ID>
<cbc:CopyIndicator>false</cbc:CopyIndicator>
<cbc:UUID />
<cbc:IssueDate>2020-06-29</cbc:IssueDate>
</Invoice>
But now i need the invoice positions in the same file.
This SQL should be included in the first one and the date should be as invoice line in the xml file:
SELECT
Rechnungpos.ID AS 'cac:InvoiceLine/cbc:ID',
Rechnungpos.Anzahl AS 'cac:InvoiceLine/cbc:InvoicedQuantity'
FROM
RechnungPos
WHERE
RechnungPos.id_Rechnung = #ID_Rechnung
The output should be this:
<Invoice xmlns:ds="http://www.w3.org/2000/09/xmldsig#" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xades="http://uri.etsi.org/01903/v1.3.2#" xmlns:cac="urn:oasis:names:specification:ubl:schema:xsd:CommonAggregateComponents-2" xmlns:cbc="urn:oasis:names:specification:ubl:schema:xsd:CommonBasicComponents-2" xmlns:ext="urn:oasis:names:specification:ubl:schema:xsd:CommonExtensionComponents-2">
<ext:UBLExtensions>
<ext:UBLExtension>
<ext:ExtensionContent />
</ext:UBLExtension>
</ext:UBLExtensions>
<cbc:UBLVersionID>2.1</cbc:UBLVersionID>
<cbc:CustomizationID>TR1.2</cbc:CustomizationID>
<cbc:ProfileID />
<cbc:ID>R200001</cbc:ID>
<cbc:CopyIndicator>false</cbc:CopyIndicator>
<cbc:UUID />
<cbc:IssueDate>2020-06-29</cbc:IssueDate>
<cac:InvoiceLine>
<cbc:ID>1<(cbc:>
<cbc:InvoicedQuantity>3</cbc:InvoicedQuantity>
</cac:InvoiceLine>
<cac:InvoiceLine>
<cbc:ID>5<(cbc:>
<cbc:InvoicedQuantity>1</cbc:InvoicedQuantity>
</cac:InvoiceLine>
<cac:InvoiceLine>
<cbc:ID>9<(cbc:>
<cbc:InvoicedQuantity>2</cbc:InvoicedQuantity>
</cac:InvoiceLine>
</Invoice>
Here is the Code to generate Test Data:
CREATE TABLE [dbo].[Rechnungen](
[id] [int] NOT NULL,
[Nummer] [nvarchar](20) NOT NULL,
[Datum] [datetime] NOT NULL
)
INSERT INTO Rechnungen (id, Nummer, Datum) VALUES (8, 'R200001', '29.06.2020')
CREATE TABLE [dbo].Rechnungpos(
[id] [int] NOT NULL,
[id_Rechnung] [int] NOT NULL,
[Anzahl] [float] NOT NULL
)
INSERT INTO RechnungPos (id, id_Rechnung, Anzahl) VALUES (1, 8, 3)
INSERT INTO RechnungPos (id, id_Rechnung, Anzahl) VALUES (5, 8, 1)
INSERT INTO RechnungPos (id, id_Rechnung, Anzahl) VALUES (9, 8, 2)
it has to run on different versions - my version is SQL Server 2019
How can i do that?
Thanks for help, Thomas.
Here is how to do it.
The only complexity is how to handle a child table and specially namespaces in the output XML. That's why XQuery and its FLWOR expression are in use.
SQL
-- DDL and sample data population, start
DECLARE #Rechnungen TABLE (id int , Nummer nvarchar(20), Datum datetime);
INSERT INTO #Rechnungen (id, Nummer, Datum) VALUES
(8, 'R200001', '2020-06-29');
DECLARE #Rechnungpos TABLE (id int, id_Rechnung int, Anzahl float);
INSERT INTO #RechnungPos (id, id_Rechnung, Anzahl) VALUES
(1, 8, 3),
(5, 8, 1),
(9, 8, 2);
-- DDL and sample data population, end
DECLARE #ID_Rechnung int = 8;
;WITH XMLNAMESPACES ('urn:oasis:names:specification:ubl:schema:xsd:CommonExtensionComponents-2' as ext
, 'urn:oasis:names:specification:ubl:schema:xsd:CommonBasicComponents-2' as cbc
, 'urn:oasis:names:specification:ubl:schema:xsd:CommonAggregateComponents-2' as cac
, 'http://uri.etsi.org/01903/v1.3.2#' as xades
, 'http://www.w3.org/2001/XMLSchema-instance' as xsi
, 'http://www.w3.org/2000/09/xmldsig#' as ds)
SELECT (
SELECT '2.1' AS [cbc:UBLVersionID],
'TR1.2' AS [cbc:CustomizationID],
'' AS [cbc:ProfileID],
p.Nummer AS [cbc:ID],
'false' AS [cbc:CopyIndicator],
'' AS [cbc:UUID],
CAST(p.Datum AS Date) AS [cbc:IssueDate],
(
SELECT c.id AS [cbc:ID]
, CAST(c.Anzahl AS INT) AS [cbc:InvoicedQuantity]
FROM #Rechnungpos AS c INNER JOIN
#Rechnungen AS p ON p.id = c.id_Rechnung
FOR XML PATH('r'), TYPE, ROOT('root')
)
FROM #Rechnungen AS p
WHERE p.id = #ID_Rechnung
FOR XML PATH(''), TYPE, ROOT('Invoice')
).query('<Invoice xmlns:ds="http://www.w3.org/2000/09/xmldsig#"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:xades="http://uri.etsi.org/01903/v1.3.2#"
xmlns:cac="urn:oasis:names:specification:ubl:schema:xsd:CommonAggregateComponents-2"
xmlns:cbc="urn:oasis:names:specification:ubl:schema:xsd:CommonBasicComponents-2"
xmlns:ext="urn:oasis:names:specification:ubl:schema:xsd:CommonExtensionComponents-2">
<ext:UBLExtensions>
<ext:UBLExtension>
<ext:ExtensionContent/>
</ext:UBLExtension>
</ext:UBLExtensions>
{
for $x in /Invoice/*[local-name()!="root"]
return $x,
for $x in /Invoice/root/r
return <cac:InvoiceLine>{$x/*}</cac:InvoiceLine>
}
</Invoice>');
Output
<Invoice xmlns:ds="http://www.w3.org/2000/09/xmldsig#" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xades="http://uri.etsi.org/01903/v1.3.2#" xmlns:cac="urn:oasis:names:specification:ubl:schema:xsd:CommonAggregateComponents-2" xmlns:cbc="urn:oasis:names:specification:ubl:schema:xsd:CommonBasicComponents-2" xmlns:ext="urn:oasis:names:specification:ubl:schema:xsd:CommonExtensionComponents-2">
<ext:UBLExtensions>
<ext:UBLExtension>
<ext:ExtensionContent />
</ext:UBLExtension>
</ext:UBLExtensions>
<cbc:UBLVersionID>2.1</cbc:UBLVersionID>
<cbc:CustomizationID>TR1.2</cbc:CustomizationID>
<cbc:ProfileID />
<cbc:ID>R200001</cbc:ID>
<cbc:CopyIndicator>false</cbc:CopyIndicator>
<cbc:UUID />
<cbc:IssueDate>2020-06-29</cbc:IssueDate>
<cac:InvoiceLine>
<cbc:ID>1</cbc:ID>
<cbc:InvoicedQuantity>3</cbc:InvoicedQuantity>
</cac:InvoiceLine>
<cac:InvoiceLine>
<cbc:ID>5</cbc:ID>
<cbc:InvoicedQuantity>1</cbc:InvoicedQuantity>
</cac:InvoiceLine>
<cac:InvoiceLine>
<cbc:ID>9</cbc:ID>
<cbc:InvoicedQuantity>2</cbc:InvoicedQuantity>
</cac:InvoiceLine>
</Invoice>
Thanks, Yitzhak Khabinsky for help - heres the complete solution:
DECLARE #ID_Rechnung int = 8,
#XMLData xml;
WITH XMLNAMESPACES ('urn:oasis:names:specification:ubl:schema:xsd:CommonExtensionComponents-2' as ext
, 'urn:oasis:names:specification:ubl:schema:xsd:CommonBasicComponents-2' as cbc
, 'urn:oasis:names:specification:ubl:schema:xsd:CommonAggregateComponents-2' as cac
, 'http://uri.etsi.org/01903/v1.3.2#' as xades
, 'http://www.w3.org/2001/XMLSchema-instance' as xsi
, 'http://www.w3.org/2000/09/xmldsig#' as ds)
SELECT
#XMLData = xmldat.xmldataCol
FROM
(
SELECT (
SELECT
-- HIER XML Daten generieren
'' AS 'ext:UBLExtensions',
'' AS 'ext:UBLExtensions/ext:UBLExtension',
'' AS 'ext:UBLExtensions/ext:UBLExtension/ext:ExtensionContent',
'2.1' AS 'cbc:UBLVersionID',
'TR1.2' AS 'cbc:CustomizationID',
'' AS 'cbc:ProfileID',
Rechnungen.Nummer AS 'cbc:ID',
'false' AS 'cbc:CopyIndicator',
'' AS 'cbc:UUID',
CAST(Rechnungen.Datum AS Date) AS 'cbc:IssueDate',
'' AS 'cbc:InvoiceTypeCode',
Rechnungen.Bemerkung1 AS 'cbc:Note',
#Waehrung AS 'cbc:DocumentCurrencyCode',
#Waehrung AS 'cbc:TaxCurrencyCode',
Rechnungen.Auftrag AS 'cac:OrderReference/cbc:ID',
-- Verkaüfer
'' AS 'cac:AccountingSupplierParty/cac:Party/cbc:EndpointID',
'' AS 'cac:AccountingSupplierParty/cac:Party/cac:PartyIdentification/cbc:ID',
'' AS 'cac:AccountingSupplierParty/cac:Party/cac:PartyName/cbc:Name',
'' AS 'cac:AccountingSupplierParty/cac:Party/cac:PostalAddress/cbc:StreetName',
'' AS 'cac:AccountingSupplierParty/cac:Party/cac:PostalAddress/cbc:CityName',
'' AS 'cac:AccountingSupplierParty/cac:Party/cac:PostalAddress/cbc:PostalZone',
'' AS 'cac:AccountingSupplierParty/cac:Party/cac:PostalAddress/cac:Country/cbc:IdentificationCode',
'' AS 'cac:AccountingSupplierParty/cac:Party/cac:PartyTaxScheme/cbc:CompanyId',
'VAT' AS 'cac:AccountingSupplierParty/cac:Party/cac:PartyTaxScheme/cac:TaxScheme/cbc:ID',
'' AS 'cac:AccountingSupplierParty/cac:Party/cac:PartyLegalEntity/cbc:RegistrationName',
'' AS 'cac:AccountingSupplierParty/cac:Party/cac:PartyLegalEntity/cbc:CompanyID',
'' AS 'cac:AccountingSupplierParty/cac:Party/cac:PartyLegalEntity/cbc:CompanyLegalForm',
'' AS 'cac:AccountingSupplierParty/cac:Party/cac:Contact/cbc:Name',
'' AS 'cac:AccountingSupplierParty/cac:Party/cac:Contact/cbc:Telephone',
'' AS 'cac:AccountingSupplierParty/cac:Party/cac:Contact/cbc:ElectronicMail',
-- Käufer
'' AS 'cac:AccountingCustomerParty/cac:Party/cbc:EndpointID',
Rechnungen.DebKreNr AS 'cac:AccountingCustomerParty/cac:Party/cac:PartyIdentification/cbc:ID',
Rechnungen.DebBez01 + ' ' + DebBez02 AS 'cac:AccountingCustomerParty/cac:Party/cac:PartyName/cbc:Name',
Rechnungen.DebStrasse AS 'cac:AccountingCustomerParty/cac:Party/cac:PostalAddress/cbc:StreetName',
Rechnungen.DebOrt AS 'cac:AccountingCustomerParty/cac:Party/cac:PostalAddress/cbc:CityName',
Rechnungen.DebPLZ AS 'cac:AccountingCustomerParty/cac:Party/cac:PostalAddress/cbc:PostalZone',
Rechnungen.DebLandKFZ AS 'cac:AccountingCustomerParty/cac:Party/cac:PostalAddress/cac:Country/cbc:IdentificationCode',
Rechnungen.DebUMSTID AS 'cac:AccountingCustomerParty/cac:Party/cac:PartyTaxScheme/cbc:CompanyID',
'VAT' AS 'cac:AccountingCustomerParty/cac:Party/cac:PartyTaxScheme/cac:TaxScheme/cbc:ID',
Rechnungen.DebBez01 + ' ' + DebBez02 AS 'cac:AccountingCustomerParty/cac:Party/cac:PartyLegalEntity/cbc:RegistrationName',
'' AS 'cac:AccountingCustomerParty/cac:Party/cac:Contact/cbc:Name',
'' AS 'cac:AccountingCustomerParty/cac:Party/cac:Contact/cbc:Telephone',
'' AS 'cac:AccountingCustomerParty/cac:Party/cac:Contact/cbc:ElectronicMail',
-- Kontoverbindung Verkäufer
'' AS 'cac:PaymentMeans/cbc:PaymentMeansCode',
'' AS 'cac:PaymentMeans/cac:PayeeFinancialAccount/cbc:ID',
'' AS 'cac:PaymentMeans/cac:PayeeFinancialAccount/cbc:Name',
'' AS 'cac:PaymentMeans/cac:PayeeFinancialAccount/cac:FinancialInstitutionBranch/cbc:ID',
--'' AS 'cac:PaymentTerms/cbc:Note',
-- Steuern
#Waehrung AS 'cac:TaxTotal/cbc_TaxAmount/#currencyID',
CAST(Rechnungen.BetragMWST AS nvarchar(15)) AS 'cac:TaxTotal/cbc_TaxAmount',
#Waehrung AS 'cac:TaxTotal/cac:Taxubtotal/cbc:TaxableAmount/#currencyID',
CAST(Rechnungen.BetragNetto AS nvarchar(15))AS 'cac:TaxTotal/cac:Taxubtotal/cbc:TaxableAmount',
#Waehrung AS 'cac:TaxTotal/cac:Taxubtotal/cbc:TaxAmount/#currencyID',
CAST(Rechnungen.BetragMWST AS nvarchar(15))AS 'cac:TaxTotal/cac:Taxubtotal/cbc:TaxAmount',
'' AS 'cac:TaxTotal/cac:Taxubtotal/cac:TaxCategory/cbc:ID',
CAST(Rechnungen.MWST AS nvarchar(2)) AS 'cac:TaxTotal/cac:Taxubtotal/cac:TaxCategory/cbc:Percent',
'VAT' AS 'cac:TaxTotal/cac:Taxubtotal/cac:TaxCategory/cac:TaxScheme/cbc:ID',
#Waehrung AS 'cac:LegalMonetaryTotal/cbc:LineExtensionAmount/#currencyID',
CAST(Rechnungen.BetragNetto AS nvarchar(15))AS 'cac:LegalMonetaryTotal/cbc:LineExtensionAmount',
#Waehrung AS 'cac:LegalMonetaryTotal/cbc:TaxExclusiveAmount/#currencyID',
CAST(Rechnungen.BetragNetto AS nvarchar(15))AS 'cac:LegalMonetaryTotal/cbc:TaxExclusiveAmount',
#Waehrung AS 'cac:LegalMonetaryTotal/cbc:TaxInclusiveAmount/#currencyID',
CAST(Rechnungen.BetragBrutto AS nvarchar(15))AS 'cac:LegalMonetaryTotal/cbc:TaxInclusiveAmount',
#Waehrung AS 'cac:LegalMonetaryTotal/cbc:PayableAmount/#currencyID',
CAST(Rechnungen.BetragBrutto AS nvarchar(15))AS 'cac:LegalMonetaryTotal/cbc:PayableAmount',
(
SELECT Rechnungpos.id AS [cbc:ID]
, CAST(Rechnungpos.Anzahl AS INT) AS [cbc:InvoicedQuantity]
FROM Rechnungpos WHERE RechnungPos.id_Rechnung = #id_Rechnung
FOR XML PATH('r'), TYPE, ROOT('root')
)
FROM Rechnungen
WHERE Rechnungen.id = #ID_Rechnung
FOR XML PATH(''), TYPE, ROOT('Invoice')
) AS xmldataCol
) AS xmldat;
SELECT #XMLData
.query('<Invoice xmlns:ds="http://www.w3.org/2000/09/xmldsig#"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:xades="http://uri.etsi.org/01903/v1.3.2#"
xmlns:cac="urn:oasis:names:specification:ubl:schema:xsd:CommonAggregateComponents-2"
xmlns:cbc="urn:oasis:names:specification:ubl:schema:xsd:CommonBasicComponents-2"
xmlns:ext="urn:oasis:names:specification:ubl:schema:xsd:CommonExtensionComponents-2">
{
for $x in /Invoice/*[local-name()!="root"]
return $x,
for $x in /Invoice/root/r
return <cac:InvoiceLine>{$x/*}</cac:InvoiceLine>
}
</Invoice>');

SQL Server: Facing problem to parse nested xml element by XQuery

My xml has 4 elements called Sheet, Group, Lineitem and BM
1) there could be multiple Sheet elements but sheet elements will not be nested.
2) Group will be child element of sheet element and Group can be nested means a group can have another child group or many nested child group.
3) Lineitem will be child element of Group element and Lineitem will not be nested.
2) BM will be child element of Lineitem element but BM element will not be nested.
i have a nested xml which i try to parse by xquery to insert data into table one by one. i store the nested element as Parent Child relationship in xml.
here is table structure
CREATE TABLE [dbo].[tblCSM_Details](
[CSM_ID] [int] NOT NULL,
[ID] [int] IDENTITY(1,1) NOT NULL,
[ParentID] [int] NULL,
[Type] [varchar](30) NULL,
[DisplayInCSM] [varchar](200) NULL,
[FontName] [varchar](max) NULL,
[FontStyle] [varchar](max) NULL,
[FontSize] [varchar](max) NULL,
[UnderLine] [varchar](max) NULL,
[BGColor] [varchar](max) NULL,
[LineItemID] [int] NULL,
[BMID] [int] NULL,
[ColOrder] [int] NULL
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]
Parent-child relation is maintained in table by the fields called ID and ParentID
My full code to parse nested element in xml.
DECLARE #XMLData XML=N'<Nodes>
<Sheet FontName="" FontStyle="" FontSize="" UnderLine="false" BGColor="" NodeText="Model1">
<Group FontName="" FontStyle="" FontSize="" UnderLine="false" BGColor="" NodeText="Consensus Model">
<LineItem FontName="" FontStyle="" FontSize="" UnderLine="false" BGColor="" LineItemID="1225" NodeText="Net Revenue" />
<LineItem FontName="" FontStyle="" FontSize="" UnderLine="false" BGColor="" LineItemID="1226" NodeText="Cost of Revenue">
<BM FontName="" FontStyle="" FontSize="" UnderLine="false" BGColor="" BMID="01" NodeText="As % of Net Revenue" />
<BM FontName="" FontStyle="" FontSize="" UnderLine="false" BGColor="" BMID="02" NodeText="Year over Year Growth" />
</LineItem>
</Group>
<Group FontName="" FontStyle="" FontSize="" UnderLine="false" BGColor="" NodeText="Segment Details">
<LineItem FontName="" FontStyle="" FontSize="" UnderLine="false" BGColor="" LineItemID="1227" NodeText="Cost of Revenue-GAAP" />
<LineItem FontName="" FontStyle="" FontSize="" UnderLine="false" BGColor="" LineItemID="1228" NodeText="Gross Profit" />
</Group>
</Sheet>
<Sheet FontName="" FontStyle="" FontSize="" UnderLine="false" BGColor="" NodeText="Model2">
<Group FontName="" FontStyle="" FontSize="" UnderLine="false" BGColor="" NodeText="Key Financials">
<LineItem FontName="" FontStyle="" FontSize="" UnderLine="false" BGColor="" LineItemID="1235" NodeText="Total Operating Expenses-GAAP" />
<LineItem FontName="" FontStyle="" FontSize="" UnderLine="false" BGColor="" LineItemID="1236" NodeText="EBITDA" />
</Group>
</Sheet>
</Nodes>'
DECLARE #BMID INT,#ColLineItemID INT
DECLARE #SheetID INT,#GroupID INT,#LineItemID INT
DECLARE #SheetOrderID INT,#GroupOrderID INT,#LineItemOrderID INT,#BMOrderID INT
DECLARE #SheetStartIndex INT ,#SheetCount INT = #XMLData.value('count(/Nodes/Sheet)', 'INT');
DECLARE #GroupStartIndex INT ,#GroupCount INT = #XMLData.value('count(/Nodes/Sheet/Group)', 'INT');
DECLARE #LineitemStartIndex INT ,#LineitemCount INT = #XMLData.value('count(/Nodes/Sheet/Group/LineItem)', 'INT');
DECLARE #BMStartIndex INT ,#BMCount INT = #XMLData.value('count(/Nodes/Sheet/Group/LineItem/BM)', 'INT');
SET #SheetStartIndex = 1
SET #GroupStartIndex = 1
SET #LineitemStartIndex = 1
SET #BMStartIndex = 1
SET #SheetOrderID = 1
SET #GroupOrderID = 1
SET #LineItemOrderID = 1
SET #BMOrderID = 1
DECLARE #DisplayInCSM VARCHAR(MAX),
#FontName VARCHAR(MAX),
#FontStyle VARCHAR(MAX),
#FontSize VARCHAR(MAX),
#UnderLine VARCHAR(MAX),
#BGColor VARCHAR(MAX)
SET #DisplayInCSM = ''
SET #FontName = ''
SET #FontStyle = ''
SET #FontSize = ''
SET #UnderLine = ''
SET #BGColor = ''
WHILE #SheetStartIndex <= #SheetCount
BEGIN --Inserting sheet data
--PRINT 'Sheet'
SELECT #DisplayInCSM = tab.col.value('#NodeText[1]', 'VARCHAR(MAX)'),
#FontName = tab.col.value('#FontName[1]', 'VARCHAR(MAX)'),
#FontStyle = tab.col.value('#FontStyle[1]', 'VARCHAR(MAX)'),
#FontSize = tab.col.value('#FontSize[1]', 'VARCHAR(MAX)'),
#UnderLine = tab.col.value('#UnderLine[1]', 'VARCHAR(MAX)'),
#BGColor = tab.col.value('#BGColor[1]', 'VARCHAR(MAX)')
FROM #XMLData.nodes('/Nodes/Sheet[position() = sql:variable("#SheetStartIndex")]') AS tab(col)
INSERT INTO tblCSM_Details(CSM_ID,[ParentID],[Type],[DisplayInCSM],[FontName],[FontStyle],[FontSize],[UnderLine],[BGColor],[LineItemID],[BMID],[ColOrder])
VALUES(1,0,'SHEET',#DisplayInCSM,#FontName,#FontStyle,#FontSize,#UnderLine,#BGColor,0,0,#SheetOrderID)
SELECT #SheetID = SCOPE_IDENTITY()
BEGIN --Inserting Group data
SET #GroupOrderID = 1
SET #GroupStartIndex = 1
WHILE #GroupStartIndex <= #GroupCount
BEGIN --Inserting Group data
SELECT #DisplayInCSM = tab.col.value('#NodeText[1]', 'VARCHAR(MAX)'),
#FontName = tab.col.value('#FontName[1]', 'VARCHAR(MAX)'),
#FontStyle = tab.col.value('#FontStyle[1]', 'VARCHAR(MAX)'),
#FontSize = tab.col.value('#FontSize[1]', 'VARCHAR(MAX)'),
#UnderLine = tab.col.value('#UnderLine[1]', 'VARCHAR(MAX)'),
#BGColor = tab.col.value('#BGColor[1]', 'VARCHAR(MAX)')
FROM #XMLData.nodes('/Nodes/Sheet/Group[position() = sql:variable("#GroupStartIndex")]') AS tab(col)
INSERT INTO tblCSM_Details(CSM_ID,[ParentID],[Type],[DisplayInCSM],[FontName],[FontStyle],[FontSize],[UnderLine],[BGColor],[LineItemID],[BMID],[ColOrder])
VALUES(1,#SheetID,'GROUP',#DisplayInCSM,#FontName,#FontStyle,#FontSize,#UnderLine,#BGColor,0,0,#GroupOrderID)
SELECT #GroupID = SCOPE_IDENTITY()
BEGIN --Inserting LineItem data
SET #LineItemOrderID = 1
SET #LineitemStartIndex = 1
WHILE #LineitemStartIndex <= #LineitemCount
BEGIN
SELECT #DisplayInCSM = tab.col.value('#NodeText[1]', 'VARCHAR(MAX)'),
#FontName = tab.col.value('#FontName[1]', 'VARCHAR(MAX)'),
#FontStyle = tab.col.value('#FontStyle[1]', 'VARCHAR(MAX)'),
#FontSize = tab.col.value('#FontSize[1]', 'VARCHAR(MAX)'),
#UnderLine = tab.col.value('#UnderLine[1]', 'VARCHAR(MAX)'),
#BGColor = tab.col.value('#BGColor[1]', 'VARCHAR(MAX)'),
#ColLineItemID = CAST(tab.col.value('#LineItemID[1]', 'VARCHAR(MAX)') AS INT)
FROM #XMLData.nodes('/Nodes/Sheet/Group/LineItem[position() = sql:variable("#LineitemStartIndex")]') AS tab(col)
INSERT INTO tblCSM_Details(CSM_ID,[ParentID],[Type],[DisplayInCSM],[FontName],[FontStyle],[FontSize],[UnderLine],[BGColor],[LineItemID],[BMID],[ColOrder])
VALUES(1,#GroupID,'LINEITEM',#DisplayInCSM,#FontName,#FontStyle,#FontSize,#UnderLine,#BGColor,#ColLineItemID,0,#LineItemOrderID)
SELECT #LineItemID = SCOPE_IDENTITY()
BEGIN --Inserting BM data
SET #BMOrderID = 1
SET #BMStartIndex = 1
WHILE #BMStartIndex <= #BMCount
BEGIN --Inserting sheet data
SELECT #DisplayInCSM = tab.col.value('#NodeText[1]', 'VARCHAR(MAX)'),
#FontName = tab.col.value('#FontName[1]', 'VARCHAR(MAX)'),
#FontStyle = tab.col.value('#FontStyle[1]', 'VARCHAR(MAX)'),
#FontSize = tab.col.value('#FontSize[1]', 'VARCHAR(MAX)'),
#UnderLine = tab.col.value('#UnderLine[1]', 'VARCHAR(MAX)'),
#BGColor = tab.col.value('#BGColor[1]', 'VARCHAR(MAX)'),
#BMID = CAST(tab.col.value('#BMID[1]', 'VARCHAR(MAX)') AS INT)
FROM #XMLData.nodes('/Nodes/Sheet/Group/LineItem/BM[position() = sql:variable("#BMStartIndex")]') AS tab(col)
INSERT INTO tblCSM_Details(CSM_ID,[ParentID],[Type],[DisplayInCSM],[FontName],[FontStyle],[FontSize],[UnderLine],[BGColor],[LineItemID],[BMID],[ColOrder])
VALUES(1,#LineItemID,'BM',#DisplayInCSM,#FontName,#FontStyle,#FontSize,#UnderLine,#BGColor,0,#BMID,#BMOrderID)
SET #BMOrderID = #BMOrderID + 1
SET #BMStartIndex = #BMStartIndex + 1
END
END
SET #LineItemOrderID = #LineItemOrderID + 1
SET #LineitemStartIndex = #LineitemStartIndex + 1
END
END
SET #GroupOrderID = #GroupOrderID + 1
SET #GroupStartIndex = #GroupStartIndex + 1;
END
END
SET #SheetOrderID = #SheetOrderID + 1
SET #SheetStartIndex = #SheetStartIndex + 1;
END
1) When run the above code then i saw 6 Group has been inserted into table. whereas i have 3 group in xml
2) BM element has been added under wrong lineitem.
i insert data into loop because i have parent child relation in table. so when i insert parent data then i store parent's inserted id into variable which i also insert during child data insertion.
i am not being able to understand where i made the mistake in code. anyone can help me. thanks

Sql Server View : Conversion failed when converting the varchar value 'No PhysicalAttributeID' to data type int

So I have created a view, but I seem to be getting an error I do not seem to understand why, I am just assigning the value, I am posting the code here
SELECT ROW_NUMBER() OVER (ORDER BY CASE WHEN commodityid = 1 THEN 0 ELSE 1 END) AS ID,
CommodityID,
CommodityName,
SubCommodityID,
SubCommodityName,
SectorID,
Sector,
GroupID,
GroupName,
StatisticID,
StatisticType,
SourceID,
Source,
SourceDescription,
PhysicalAttributeID,
PhysicalAttribute,
UtilizationID,
UtilizationPractice,
ProductionPracticeID,
ProductionPractice,
Description,
SourceSeriesID,
TimeID,
TimeFrequency,
Date,
GeographyID,
GeographyType,
City,
County,
State,
Region,
Country,
UnitID,
Unit,
LifecyclePhaseID,
LifecyclePhaseDescription AS Value
FROM (SELECT DISTINCT
dv.ERSDataValues_ERSCommodity_ID AS CommodityID,
CASE
WHEN CHARINDEX(',', csc.ERSCommoditySubCommodity_Desc) > 0 THEN SUBSTRING(csc.ERSCommoditySubCommodity_Desc, 1, CHARINDEX(',', csc.ERSCommoditySubCommodity_Desc) - 1)
ELSE csc.ERSCommoditySubCommodity_Desc
END AS CommodityName,
cds.ERSCommoditySubCommodity_ID AS SubCommodityID,
CASE
WHEN CHARINDEX(',', csc.ERSCommoditySubCommodity_Desc) > 0 THEN LTRIM(SUBSTRING(csc.ERSCommoditySubCommodity_Desc, CHARINDEX(',', csc.ERSCommoditySubCommodity_Desc) + 1, LEN(csc.ERSCommoditySubCommodity_Desc)))
ELSE 'No SubCommodity'
END AS SubCommodityName,
su.ERSSector_ID AS SectorID,
su.ERSSector_Desc AS Sector,
gu.ERSGroup_ID AS GroupID,
gu.ERSGroup_Desc AS GroupName,
stu.ERSStatisticType_ID AS StatisticID,
stu.ERSStatisticType_Attribute AS StatisticType,
slu.ERSSource_ID AS SourceID,
slu.ERSSource_Desc AS Source,
slu.ERSSource_LongDesc AS SourceDescription,
phlu.ERSPhysicalAttribute_ID AS PhysicalAttributeID,
cds.ERSCommodity_PhysicalAttribute_Desc AS PhysicalAttribute,
upu.ERSUtilPractice_ID AS UtilizationID,
upu.ERSUtilPractice_Desc AS UtilizationPractice,
pu.ERSProdPractice_ID AS ProductionPracticeID,
pu.ERSProdPractice_Desc AS ProductionPractice,
CASE
WHEN cds.ERSCommodity_SourceSeriesID_LongDesc IS NULL THEN 'No Description'
ELSE cds.ERSCommodity_SourceSeriesID_LongDesc
END AS Description,
CASE
WHEN cds.ERSCommodity_SourceSeriesID IS NULL THEN 'No SourceSeriesID'
ELSE cds.ERSCommodity_SourceSeriesID
END AS SourceSeriesID,
tu.ERSTimeDimension_ID AS TimeID,
REPLACE(tdt.ERSTimeDimensionType_Desc, 'ERS', '') AS TimeFrequency,
tu.ERSTimeDimension_Date AS Date,
gdu.ERSGeographyDimension_ID AS GeographyID,
gtu.ERSGeographyType_Desc AS GeographyType,
CASE
WHEN COALESCE(gdu.ERSGeographyDimension_City, '') = '' THEN 'No City'
ELSE gdu.ERSGeographyDimension_City
END AS City,
CASE
WHEN COALESCE(gdu.ERSGeographyDimension_County, '') = '' THEN 'No County'
ELSE gdu.ERSGeographyDimension_County
END AS County,
CASE
WHEN COALESCE(gdu.ERSGeographyDimension_State, '') = '' THEN 'No State'
ELSE gdu.ERSGeographyDimension_State
END AS State,
CASE
WHEN COALESCE(gdu.ERSGeographyDimension_Region, '') = '' THEN 'No Region'
ELSE gdu.ERSGeographyDimension_Region
END AS Region,
CASE
WHEN COALESCE(gdu.ERSGeographyDimension_Country, '') = '' THEN 'No Country'
ELSE gdu.ERSGeographyDimension_Country
END AS Country,
ulu.ERSUnit_ID AS UnitID,
ulu.ERSUnit_Desc AS Unit,
dv.ERSDataValues_DataRowLifecyclePhaseID AS LifecyclePhaseID,
dlu.ERSDataLifecyclePhase_Desc AS LifecyclePhaseDescription,
dv.ERSDataValues_AttributeValue AS Value
FROM CoSD.ERSCommodityDataSeries cds
INNER JOIN cosd.ERSPhysicalAttribute_LU phlu ON phlu.ERSPhysicalAttribute_ID = cds.ERSCommodity_ERSPhysicalAttribute_ID
INNER JOIN CoSD.ERSDataValues dv ON cds.ERSCommodity_ID = dv.ERSDataValues_ERSCommodity_ID
INNER JOIN CoSD.ERSSector_LU su ON cds.ERSCommodity_ERSSector_ID = su.ERSSector_ID
INNER JOIN CoSD.ERSGroup_LU gu ON cds.ERSCommodity_ERSGroup_ID = gu.ERSGroup_ID
INNER JOIN CoSD.ERSProdPractice_LU pu ON cds.ERSCommodity_ERSProdPractice_ID = pu.ERSProdPractice_ID
INNER JOIN CoSD.ERSUtilPractice_LU upu ON cds.ERSCommodity_ERSUtilPractice_ID = upu.ERSUtilPractice_ID
AND cds.ERSCommodity_ERSUtilPractice_ID = upu.ERSUtilPractice_ID
INNER JOIN CoSD.ERSUnit_LU ulu ON dv.ERSDataValues_ERSUnit_ID = ulu.ERSUnit_ID
INNER JOIN CoSD.ERSSource_LU slu ON cds.ERSCommodity_ERSSource_ID = slu.ERSSource_ID
INNER JOIN CoSD.ERSStatisticType_LU stu ON cds.ERSCommodity_ERSStatisticType_ID = stu.ERSStatisticType_ID
INNER JOIN CoSD.ERSTimeDimension_LU tu ON dv.ERSDataValues_ERSTimeDimension_ID = tu.ERSTimeDimension_ID
INNER JOIN CoSD.ERSGeographyDimension_LU gdu ON dv.ERSDataValues_ERSGeography_ID = gdu.ERSGeographyDimension_ID
INNER JOIN CoSD.ERSTimeDimensionType_LU tdt ON tu.ERSTimeDimension_TimeDimensionType_ID = tdt.ERSTimeDimensionType_ID
INNER JOIN CoSD.ERSGeographyType_LU gtu ON gdu.ERSGeographyDimension_ERSGeographyType_ID = gtu.ERSGeographyType_ID
INNER JOIN CoSD.ERSCommoditySubCommodity_LU csc ON csc.ERSCommoditySubCommodity_ID = cds.ERSCommoditySubCommodity_ID
INNER JOIN cosd.ERSDataLifecycle_LU dlu ON dlu.ERSDataLifecyclePhase_ID = dv.ERSDataValues_DataRowLifecyclePhaseID
WHERE dv.ERSDataRowPrivacy_ID = 1
AND dv.ERSDataValues_AttributeValue IS NOT NULL
UNION ALL
SELECT DISTINCT
cds.ERSCommodity_ID AS CommodityID,
CASE
WHEN CHARINDEX(',', csc.ERSCommoditySubCommodity_Desc) > 0 THEN SUBSTRING(csc.ERSCommoditySubCommodity_Desc, 1, CHARINDEX(',', csc.ERSCommoditySubCommodity_Desc) - 1)
ELSE csc.ERSCommoditySubCommodity_Desc
END AS CommodityName,
csc.ERSCommoditySubCommodity_ID AS SubCommodityID,
CASE
WHEN CHARINDEX(',', csc.ERSCommoditySubCommodity_Desc) > 0 THEN LTRIM(SUBSTRING(csc.ERSCommoditySubCommodity_Desc, CHARINDEX(',', csc.ERSCommoditySubCommodity_Desc) + 1, LEN(csc.ERSCommoditySubCommodity_Desc)))
ELSE 'No SubCommodity'
END AS SubCommodityName,
slu.ERSSector_ID AS SectorID,
slu.ERSSector_Desc AS Sector,
glu.ERSGroup_ID AS GroupID,
glu.ERSGroup_Desc AS GroupName,
stu.ERSStatisticType_ID AS StatisticID,
stu.ERSStatisticType_Attribute AS StatisticType,
selu.ERSSource_ID AS SourceID,
cvo.ERSConstructedVariable_InputSources AS Source,
selu.ERSSource_LongDesc AS SourceDescription,
cds.ERSCommodity_ERSPhysicalAttribute_ID AS PhysicalAttributeID,
cds.ERSCommodity_PhysicalAttribute_Desc AS PhysicalAttribute,
ulu.ERSUtilPractice_ID AS UtilizationID,
ulu.ERSUtilPractice_Desc AS UtilizationPractice,
plu.ERSProdPractice_ID AS ProductionPracticeID,
plu.ERSProdPractice_Desc AS ProductionPractice,
cvo.ERSConstructedVariable_OutputName AS Description,
CASE
WHEN cds.ERSCommodity_SourceSeriesID LIKE '%(N%' THEN 'No SourceSeriesID'
ELSE cds.ERSCommodity_SourceSeriesID
END AS SourceSeriesID,
tlu.ERSTimeDimension_ID AS TimeID,
REPLACE(tdlu.ERSTimeDimensionType_Desc, 'ERS', '') AS TimeFrequency,
cvo.ERSConstructedVariable_TimeDimensionDate AS Date,
gdlu.ERSGeographyDimension_ID AS GeographyID,
gtlu.ERSGeographyType_Desc AS GeographyType,
CASE
WHEN COALESCE(gdlu.ERSGeographyDimension_City, '') = '' THEN 'No City'
ELSE gdlu.ERSGeographyDimension_City
END AS City,
CASE
WHEN COALESCE(gdlu.ERSGeographyDimension_County, '') = '' THEN 'No County'
ELSE gdlu.ERSGeographyDimension_County
END AS County,
CASE
WHEN COALESCE(gdlu.ERSGeographyDimension_State, '') = '' THEN 'No State'
ELSE gdlu.ERSGeographyDimension_State
END AS State,
CASE
WHEN COALESCE(gdlu.ERSGeographyDimension_Region, '') = '' THEN 'No Region'
ELSE gdlu.ERSGeographyDimension_Region
END AS Region,
CASE
WHEN COALESCE(gdlu.ERSGeographyDimension_Country, '') = '' THEN 'No Country'
ELSE gdlu.ERSGeographyDimension_Country
END AS Country,
unlu.ERSUnit_ID AS UnitID,
unlu.ERSUnit_Desc AS Unit,
cvo.ERSConstructedVariable_DataRowLifecyclePhaseID AS LifecyclePhaseID,
dlu.ERSDataLifecyclePhase_Desc AS LifecyclePhaseDescription,
cvo.ERSConstructedVariable_OutputValue AS Value
FROM CoSD.ERSConstructedVariablesOutcomes cvo
INNER JOIN CoSD.ERSCommodityDataSeries cds ON cvo.ERSConstructedVariable_NewDataSeriesID = cds.ERSCommodity_ID
INNER JOIN CoSD.ERSSector_LU slu ON cds.ERSCommodity_ERSSector_ID = slu.ERSSector_ID
INNER JOIN CoSD.ERSGroup_LU glu ON cds.ERSCommodity_ERSGroup_ID = glu.ERSGroup_ID
INNER JOIN CoSD.ERSCommoditySubCommodity_LU csc ON cds.ERSCommoditySubCommodity_ID = csc.ERSCommoditySubCommodity_ID
INNER JOIN CoSD.ERSStatisticType_LU stu ON cds.ERSCommodity_ERSStatisticType_ID = stu.ERSStatisticType_ID
INNER JOIN CoSD.ERSUtilPractice_LU ulu ON cds.ERSCommodity_ERSUtilPractice_ID = ulu.ERSUtilPractice_ID
INNER JOIN CoSD.ERSProdPractice_LU plu ON cds.ERSCommodity_ERSProdPractice_ID = plu.ERSProdPractice_ID
INNER JOIN CoSD.ERSGeographyDimension_LU gdlu ON cvo.ERSConstructedVariable_OutputGeographyDimensionID = gdlu.ERSGeographyDimension_ID
INNER JOIN CoSD.ERSUnit_LU unlu ON cvo.ERSConstructedVariable_OutputUnitID = unlu.ERSUnit_ID
INNER JOIN CoSD.ERSGeographyType_LU gtlu ON gdlu.ERSGeographyDimension_ERSGeographyType_ID = gtlu.ERSGeographyType_ID
INNER JOIN cosd.ERSTimeDimension_LU tlu ON tlu.ERSTimeDimension_ID = cvo.ERSConstructedVariable_TimeDimensionID
AND tlu.ERSTimeDimension_Date = cvo.ERSConstructedVariable_TimeDimensionDate
AND YEAR(tlu.ERSTimeDimension_Date) = YEAR(cvo.ERSConstructedVariable_TimeDimensionDate)
AND MONTH(tlu.ERSTimeDimension_Date) = MONTH(ERSConstructedVariable_TimeDimensionDate)
INNER JOIN cosd.ERSTimeDimensionType_LU tdlu ON tdlu.ERSTimeDimensionType_ID = tlu.ERSTimeDimension_TimeDimensionType_ID
INNER JOIN cosd.ERSSource_LU selu ON cvo.ERSConstructedVariable_InputSourceID = selu.ERSSource_ID
INNER JOIN cosd.ERSDataLifecycle_LU dlu ON dlu.ERSDataLifecyclePhase_ID = cvo.ERSConstructedVariable_DataRowLifecyclePhaseID
WHERE cvo.ERSConstructedVariable_DataRowPrivacyID = 1
AND cvo.ERSConstructedVariable_NewDataSeriesID IS NOT NULL
AND cvo.ERSConstructedVariable_OutputValue IS NOT NULL
UNION ALL
SELECT DISTINCT
CDS.ERSCommodity_ID AS CommodityID,
CASE
WHEN CHARINDEX(',', csc.ERSCommoditySubCommodity_Desc) > 0 THEN SUBSTRING(csc.ERSCommoditySubCommodity_Desc, 1, CHARINDEX(',', csc.ERSCommoditySubCommodity_Desc) - 1)
ELSE csc.ERSCommoditySubCommodity_Desc
END AS CommodityName,
csc.ERSCommoditySubCommodity_ID AS SubCommodityID,
CASE
WHEN CHARINDEX(',', csc.ERSCommoditySubCommodity_Desc) > 0 THEN LTRIM(SUBSTRING(csc.ERSCommoditySubCommodity_Desc, CHARINDEX(',', csc.ERSCommoditySubCommodity_Desc) + 1, LEN(csc.ERSCommoditySubCommodity_Desc)))
ELSE 'No SubCommodity'
END AS SubCommodityName,
slu.ERSSector_ID AS SectorID,
slu.ERSSector_Desc AS Sector,
glu.ERSGroup_ID AS GroupID,
glu.ERSGroup_Desc AS GroupName,
stu.ERSStatisticType_ID AS StatisticID,
stu.ERSStatisticType_Attribute AS StatisticType,
selu.ERSSource_ID AS SourceID,
cvo.ERSConstructedVariable_InputSources AS Source,
selu.ERSSource_LongDesc AS SourceDescription,
CDS.ERSCommodity_ERSPhysicalAttribute_ID AS PhysicalAttributeID,
CDS.ERSCommodity_PhysicalAttribute_Desc AS PhysicalAttribute,
ulu.ERSUtilPractice_ID AS UtilizationID,
ulu.ERSUtilPractice_Desc AS UtilizationPractice,
plu.ERSProdPractice_ID AS ProductionPracticeID,
plu.ERSProdPractice_Desc AS ProductionPractice,
cvo.ERSConstructedVariable_OutputName AS Description,
CASE
WHEN CDS.ERSCommodity_SourceSeriesID IS NULL THEN 'No SourceSeriesID'
ELSE CDS.ERSCommodity_SourceSeriesID
END AS SourceSeriesID,
tlu.ERSTimeDimension_ID AS TimeID,
REPLACE(tdlu.ERSTimeDimensionType_Desc, 'ERS', '') AS TimeFrequency,
cvo.ERSConstructedVariable_TimeDimensionDate AS Date,
gdlu.ERSGeographyDimension_ID AS GeographyID,
gtlu.ERSGeographyType_Desc AS GeographyType,
CASE
WHEN COALESCE(gdlu.ERSGeographyDimension_City, '') = '' THEN 'No City'
ELSE gdlu.ERSGeographyDimension_City
END AS City,
CASE
WHEN COALESCE(gdlu.ERSGeographyDimension_County, '') = '' THEN 'No County'
ELSE gdlu.ERSGeographyDimension_County
END AS County,
CASE
WHEN COALESCE(gdlu.ERSGeographyDimension_State, '') = '' THEN 'No State'
ELSE gdlu.ERSGeographyDimension_State
END AS State,
CASE
WHEN COALESCE(gdlu.ERSGeographyDimension_Region, '') = '' THEN 'No Region'
ELSE gdlu.ERSGeographyDimension_Region
END AS Region,
CASE
WHEN COALESCE(gdlu.ERSGeographyDimension_Country, '') = '' THEN 'No Country'
ELSE gdlu.ERSGeographyDimension_Country
END AS Country,
unlu.ERSUnit_ID AS UnitID,
unlu.ERSUnit_Desc AS Unit,
cvo.ERSConstructedVariable_DataRowLifecyclePhaseID AS LifecyclePhaseID,
dlu.ERSDataLifecyclePhase_Desc AS LifecyclePhaseDescription,
cvo.ERSConstructedVariable_OutputValue AS Value
FROM CoSD.ERSConstructedVariablesOutcomes cvo
INNER JOIN CoSD.ERSBusinessLogic BL ON cvo.ERSConstructedVariable_BusinessLogicID = BL.ERSBusinessLogic_ID
INNER JOIN cosd.ERSCommodityDataSeries CDS ON CDS.ERSCommodity_ID = BL.ERSBusinessLogic_InputDataSeries
INNER JOIN CoSD.ERSSector_LU slu ON CDS.ERSCommodity_ERSSector_ID = slu.ERSSector_ID
INNER JOIN CoSD.ERSGroup_LU glu ON CDS.ERSCommodity_ERSGroup_ID = glu.ERSGroup_ID
INNER JOIN CoSD.ERSCommoditySubCommodity_LU csc ON CDS.ERSCommoditySubCommodity_ID = csc.ERSCommoditySubCommodity_ID
INNER JOIN CoSD.ERSStatisticType_LU stu ON CDS.ERSCommodity_ERSStatisticType_ID = stu.ERSStatisticType_ID
INNER JOIN CoSD.ERSUtilPractice_LU ulu ON CDS.ERSCommodity_ERSUtilPractice_ID = ulu.ERSUtilPractice_ID
INNER JOIN CoSD.ERSProdPractice_LU plu ON CDS.ERSCommodity_ERSProdPractice_ID = plu.ERSProdPractice_ID
INNER JOIN CoSD.ERSGeographyDimension_LU gdlu ON cvo.ERSConstructedVariable_OutputGeographyDimensionID = gdlu.ERSGeographyDimension_ID
INNER JOIN CoSD.ERSUnit_LU unlu ON cvo.ERSConstructedVariable_OutputUnitID = unlu.ERSUnit_ID
INNER JOIN CoSD.ERSGeographyType_LU gtlu ON gdlu.ERSGeographyDimension_ERSGeographyType_ID = gtlu.ERSGeographyType_ID
INNER JOIN cosd.ERSTimeDimension_LU tlu ON tlu.ERSTimeDimension_ID = cvo.ERSConstructedVariable_TimeDimensionID
AND tlu.ERSTimeDimension_Date = cvo.ERSConstructedVariable_TimeDimensionDate
AND YEAR(tlu.ERSTimeDimension_Date) = YEAR(cvo.ERSConstructedVariable_TimeDimensionDate)
AND MONTH(tlu.ERSTimeDimension_Date) = MONTH(ERSConstructedVariable_TimeDimensionDate)
INNER JOIN cosd.ERSTimeDimensionType_LU tdlu ON tdlu.ERSTimeDimensionType_ID = tlu.ERSTimeDimension_TimeDimensionType_ID
INNER JOIN cosd.ERSSource_LU selu ON cvo.ERSConstructedVariable_InputSourceID = selu.ERSSource_ID
INNER JOIN cosd.ERSDataLifecycle_LU dlu ON dlu.ERSDataLifecyclePhase_ID = cvo.ERSConstructedVariable_DataRowLifecyclePhaseID
WHERE cvo.ERSConstructedVariable_DataRowPrivacyID = 1
AND BL.ERSBusinessLogic_InputsCount = 1
AND BL.ERSBusinessLogic_InputDataSeries NOT LIKE '%CV%'
AND cvo.ERSConstructedVariable_NewDataSeriesID IS NULL
AND cvo.ERSConstructedVariable_OutputValue IS NOT NULL
UNION ALL
SELECT DISTINCT
'-1' AS CommodityID,
ERSMacro_Desc AS CommodityName,
'-1' AS SubCommodityID,
ERSMacro_LongDesc AS SubCommodityName,
'4' AS SectorID,
'Macro' AS Sector,
'17' AS GroupID,
'Macro' AS GroupName,
NULL AS StatisticID,
'No StatisticType' AS StatisticType,
slu.ERSSource_ID AS SourceID,
slu.ERSSource_Desc AS Source,
slu.ERSSource_LongDesc AS SourceDescription,
TRY_CONVERT(varchar, 'No PhysicalAttributeID') AS PhysicalAttributeID,
'No PhysicalAttribute' AS PhysicalAttribute,
'No UtilizationID' AS UtilizationID,
'No UtilizationPractice' AS UtilizationPractice,
'No ProductionPracticeID' AS ProductionPracticeID,
'No ProductionPractice' AS ProductionPractice,
'No Description' AS Description,
'No SourceSeriesID' AS SourceSeriesID,
tlu.ERSTimeDimension_ID AS TimeID,
REPLACE(ttlu.ERSTimeDimensionType_Desc, 'ERS', '') AS TimeFrequency,
tlu.ERSTimeDimension_Date AS Date,
glu.ERSGeographyDimension_ID AS GeographyID,
gtlu.ERSGeographyType_Desc AS GeographyType,
CASE
WHEN COALESCE(glu.ERSGeographyDimension_City, '') = '' THEN 'No City'
ELSE glu.ERSGeographyDimension_City
END AS City,
CASE
WHEN COALESCE(glu.ERSGeographyDimension_County, '') = '' THEN 'No County'
ELSE glu.ERSGeographyDimension_County
END AS County,
CASE
WHEN COALESCE(glu.ERSGeographyDimension_State, '') = '' THEN 'No State'
ELSE glu.ERSGeographyDimension_State
END AS State,
CASE
WHEN COALESCE(glu.ERSGeographyDimension_Region, '') = '' THEN 'No Region'
ELSE glu.ERSGeographyDimension_Region
END AS Region,
CASE
WHEN COALESCE(glu.ERSGeographyDimension_Country, '') = '' THEN 'No Country'
ELSE glu.ERSGeographyDimension_Country
END AS Country,
ulu.ERSUnit_ID AS UnitID,
ulu.ERSUnit_Desc AS Unit,
'No LifecyclephaseID' AS LifecyclePhaseID,
'No LifecyclePhaseDescription' AS LifecyclePhaseDescription,
mlu.ERSMacro_Value AS Value
FROM cosd.ERSMacro_LU mlu
INNER JOIN cosd.ERSSource_LU slu ON slu.ERSSource_ID = mlu.ERSMacro_Source_ID
INNER JOIN cosd.ERSTimeDimension_LU tlu ON tlu.ERSTimeDimension_ID = mlu.ERSMacro_TimeDimension_ID
INNER JOIN cosd.ERSTimeDimensionType_LU ttlu ON ttlu.ERSTimeDimensionType_ID = tlu.ERSTimeDimension_TimeDimensionType_ID
INNER JOIN cosd.ERSGeographyDimension_LU glu ON glu.ERSGeographyDimension_ID = mlu.ERSMacro_GeographyDimension_ID
INNER JOIN cosd.ERSGeographyType_LU gtlu ON gtlu.ERSGeographyType_ID = glu.ERSGeographyDimension_ERSGeographyType_ID
INNER JOIN cosd.ERSUnit_LU ulu ON ulu.ERSUnit_ID = mlu.ERSMacro_Unit_ID) derived;
I get this error :
Conversion failed when converting the varchar value 'No PhysicalAttributeID' to data type int.
But the best part is if I run the last part of the code as below
SELECT ROW_NUMBER() OVER (ORDER BY CASE WHEN CommodityID = 1 THEN 0 ELSE 1 END) AS ID,
CommodityID,
CommodityName,
SubCommodityID,
SubCommodityName,
SectorID,
Sector,
GroupID,
GroupName,
StatisticID,
StatisticType,
SourceID,
Source,
SourceDescription,
PhysicalAttributeID,
PhysicalAttribute,
UtilizationID,
UtilizationPractice,
ProductionPracticeID,
ProductionPractice,
Description,
SourceSeriesID,
TimeID,
TimeFrequency,
Date,
GeographyID,
GeographyType,
City,
County,
State,
Region,
Country,
UnitID,
Unit,
LifecyclePhaseID,
LifecyclePhaseDescription,
Value
FROM (SELECT DISTINCT
'-1' AS CommodityID,
ERSMacro_Desc AS CommodityName,
'-1' AS SubCommodityID,
ERSMacro_LongDesc AS SubCommodityName,
'4' AS SectorID,
'Macro' AS Sector,
'17' AS GroupID,
'Macro' AS GroupName,
'No Statistic' AS StatisticID,
'No StatisticType' AS StatisticType,
slu.ERSSource_ID AS SourceID,
slu.ERSSource_Desc AS Source,
slu.ERSSource_LongDesc AS SourceDescription,
'No PhysicalAttributeID' AS PhysicalAttributeID,
'No PhysicalAttribute' AS PhysicalAttribute,
'No UtilizationID' AS UtilizationID,
'No UtilizationPractice' AS UtilizationPractice,
'No ProductionPracticeID' AS ProductionPracticeID,
'No ProductionPractice' AS ProductionPractice,
'No Description' AS Description,
'No SourceSeriesID' AS SourceSeriesID,
tlu.ERSTimeDimension_ID AS TimeID,
REPLACE(ttlu.ERSTimeDimensionType_Desc, 'ERS', '') AS TimeFrequency,
tlu.ERSTimeDimension_Date AS Date,
glu.ERSGeographyDimension_ID AS GeographyID,
gtlu.ERSGeographyType_Desc AS GeographyType,
CASE
WHEN COALESCE(glu.ERSGeographyDimension_City, '') = '' THEN 'No City'
ELSE glu.ERSGeographyDimension_City
END AS City,
CASE
WHEN COALESCE(glu.ERSGeographyDimension_County, '') = '' THEN 'No County'
ELSE glu.ERSGeographyDimension_County
END AS County,
CASE
WHEN COALESCE(glu.ERSGeographyDimension_State, '') = '' THEN 'No State'
ELSE glu.ERSGeographyDimension_State
END AS State,
CASE
WHEN COALESCE(glu.ERSGeographyDimension_Region, '') = '' THEN 'No Region'
ELSE glu.ERSGeographyDimension_Region
END AS Region,
CASE
WHEN COALESCE(glu.ERSGeographyDimension_Country, '') = '' THEN 'No Country'
ELSE glu.ERSGeographyDimension_Country
END AS Country,
ulu.ERSUnit_ID AS UnitID,
ulu.ERSUnit_Desc AS Unit,
'No LifecyclephaseID' AS LifecyclePhaseID,
'No LifecyclePhaseDescription' AS LifecyclePhaseDescription,
mlu.ERSMacro_Value AS Value
FROM cosd.ERSMacro_LU mlu
INNER JOIN cosd.ERSSource_LU slu ON slu.ERSSource_ID = mlu.ERSMacro_Source_ID
INNER JOIN cosd.ERSTimeDimension_LU tlu ON tlu.ERSTimeDimension_ID = mlu.ERSMacro_TimeDimension_ID
INNER JOIN cosd.ERSTimeDimensionType_LU ttlu ON ttlu.ERSTimeDimensionType_ID = tlu.ERSTimeDimension_TimeDimensionType_ID
INNER JOIN cosd.ERSGeographyDimension_LU glu ON glu.ERSGeographyDimension_ID = mlu.ERSMacro_GeographyDimension_ID
INNER JOIN cosd.ERSGeographyType_LU gtlu ON gtlu.ERSGeographyType_ID = glu.ERSGeographyDimension_ERSGeographyType_ID
INNER JOIN cosd.ERSUnit_LU ulu ON ulu.ERSUnit_ID = mlu.ERSMacro_Unit_ID) derived;
This runs perfectly without any problems. If I change 'No PhysicalAttributeID' to null, it runs properly, I have tried this solution and also this
I seem to be heading no where, any ideas ?
It is because in the first query column 15 is PhysicalAttributeID which is almost certainly an int. Then you attempt to use UNION ALL to your second query. It will attempt an implicit conversion and fail.
An easy solution would be to adjust the first query. You would need to something like on each of those queries.
PhysicalAttributeID = convert(varchar(20), PhysicalAttributeID)
This is the line you have error at:
TRY_CONVERT(varchar, 'No PhysicalAttributeID') AS PhysicalAttributeID
this is incompatible with its matches, like
phlu.ERSPhysicalAttribute_ID AS PhysicalAttributeID
or
cds.ERSCommodity_ERSPhysicalAttribute_ID AS PhysicalAttributeID
or
CDS.ERSCommodity_ERSPhysicalAttribute_ID AS PhysicalAttributeID
You will need to convert the numeric values above into varchar to solve your problem.

how to use coalesce with in, in the where part

How to use Coalesce Command in the following code
PIECE_DETAIL in coalesce( PIECE_DETAIL, (SELECT B.MODEL_ID FROM PIECES_DETAILS B WHERE PIECE_ID = #PIECE_ID AND B.BRAND_ID=COALESCE(B.BRAND_ID,#BRAND_ID))
in this code
SELECT DISTINCT
[dbo].[test2](A.PIECE_DETAIL ) TOTAL_QUANTITY,
PIECE_LATIN = (SELECT PIECE_LATIN FROM PIECES WHERE PIECE_ID =
(SELECT PIECE_ID FROM PIECES_DETAILS WHERE MODEL_ID = A.PIECE_DETAIL )),
BRAND_LATIN = (SELECT BRAND_LATIN FROM BRANDS WHERE BRAND_ID =
(SELECT BRAND_ID FROM PIECES_DETAILS WHERE MODEL_ID = A.PIECE_DETAIL )),
BRAND_ID = (SELECT BRAND_ID FROM PIECES_DETAILS WHERE MODEL_ID = A.PIECE_DETAIL ),
PIECE_ID = (SELECT PIECE_ID FROM PIECES_DETAILS WHERE MODEL_ID = A.PIECE_DETAIL ),
MODEL_NAME = (SELECT MODEL_NAME FROM PIECES_DETAILS WHERE MODEL_ID = A.PIECE_DETAIL ),
PIECE_DETAIL MODEL_ID,
A.PIECE_STATUS ,
PIECE_STATUS_Name = (SELECT STATUS_Name FROM PIECE_STATUS WHERE STATUS_ID = A.PIECE_STATUS) ,
A.PIECE_DETAIL
FROM DOCUMENT_ITEMS A
WHERE
PIECE_STATUS = 1 and
DOC_SEQ IN (SELECT DOC_SEQ FROM DOCUMENT_HEADER WHERE DOC_TYPE IN (1,3))
AND PIECE_DETAIL in coalesce( PIECE_DETAIL, (SELECT B.MODEL_ID FROM PIECES_DETAILS B WHERE PIECE_ID = #PIECE_ID AND B.BRAND_ID=COALESCE(B.BRAND_ID,#BRAND_ID))
AND [DBO].[GET_WAREHOUSE_QUANTITIES_SPECIAL_ID_EXIST](A.PIECE_DETAIL ,A.SPECIAL_ID )> 0
GROUP BY PIECE_DETAIL ,SPECIAL_ID ,PIECE_STATUS
thanks all
Something like this then:
WHERE PIECE_DETAIL IN
(
SELECT
coalesce(PIECE_DETAIL,B.MODEL_ID)
FROM
PIECES_DETAILS B
WHERE
PIECE_ID = #PIECE_ID
AND B.BRAND_ID=COALESCE(B.BRAND_ID,#BRAND_ID)
)
Edit
Maybe something like this:
WHERE
(
(
FROM_DATE IS NULL AND TO_DATE IS NULL
)
OR
(
BUY_DOC_DATE BETWEEN FROM_DATE AND TO_DATE
)
)

Resources