Re-writing Query - oracle

Overall Task :- I need to retrieve data from 45 fields in system A and dump that data into a temp table which is then picked up by a unix process which produces an xml data file to be imported into system B.
Specific Question : What would be the best way of retrieving the data to be written into the 45 fields. Majority of the data is independent and can't be retrieved using a single statement. The way i currently retrieve this data is as follows (example below)
My temp tables hold the affected properties ID that i need to extract data for. i.e PROP_LIST_TEMP and ASSOC_PROP_TEMP.
SELECT SUBSTR (pro.pro_propref, 1, 25) UPRN,
(SELECT SUBSTR (adr_building, 1, 100)
FROM addresses, address_usages
WHERE aus_adr_refno = adr_refno
AND aus_aut_far_code = 'PHYSICAL'
AND aus_aut_fao_code = 'PRO'
AND (aus_end_date IS NULL OR aus_end_date > SYSDATE)
AND aus_pro_refno = pro.pro_refno)
BUILDING_NAME,
(SELECT CASE
WHEN (adr_street_number like 'BLOC%'
OR adr_street_number like '%-%'
OR adr_street_number like '%/%')
THEN NULL
ELSE regexp_replace (adr_street_number, '[^[:digit:]]+')
END
FROM addresses, address_usages
WHERE aus_adr_refno = adr_refno
AND aus_aut_far_code = 'PHYSICAL'
AND aus_aut_fao_code = 'PRO'
AND (aus_end_date IS NULL OR aus_end_date > SYSDATE)
AND aus_pro_refno = pro.pro_refno)
STREET_NUMBER,
(SELECT CASE
WHEN (adr_street_number like 'BLOC%'
OR adr_street_number like '%-%'
OR adr_street_number like '%/%')
THEN SUBSTR (adr_street_number, 1, 20)
ELSE REGEXP_REPLACE (adr_street_number, '[^[:alpha:]]+', '')
END
FROM addresses, address_usages
WHERE aus_adr_refno = adr_refno
AND aus_aut_far_code = 'PHYSICAL'
AND aus_aut_fao_code = 'PRO'
AND (aus_end_date IS NULL OR aus_end_date > SYSDATE)
AND aus_pro_refno = pro.pro_refno)
STREET_NUMBER_SUFFIX,
(SELECT SUBSTR (ptv_pty_code, 1, 3)
FROM prop_type_values
WHERE ptv_refno = pro.pro_hou_ptv_refno)
HOUSE_TYPE
FROM properties pro
WHERE pro_refno IN (select * from PIMSS_PROP_LIST_TEMP
UNION
select * from PIMSS_ASSOC_PROP_TEMP)
AND pro.pro_hou_hrv_hot_code IN
(SELECT frv_code
FROM first_ref_values
WHERE frv_frd_domain IN ('ASS_OWN_REF')
AND frv_current_ind = 'Y');

Since the where clauses of the subqueries in the select statement are identical, you could simply pull that out into the where clause, like so:
SELECT SUBSTR (pro.pro_propref, 1, 25) UPRN,
SUBSTR (addr.adr_building, 1, 100) BUILDING_NAME,
CASE WHEN (addr.adr_street_number like 'BLOC%'
OR addr.adr_street_number like '%-%'
OR addr.adr_street_number like '%/%')
THEN NULL
ELSE regexp_replace (addr.adr_street_number, '[^[:digit:]]+')
END STREET_NUMBER,
CASE WHEN (addr.adr_street_number like 'BLOC%'
OR addr.adr_street_number like '%-%'
OR addr.adr_street_number like '%/%')
THEN SUBSTR (addr.adr_street_number, 1, 20)
ELSE REGEXP_REPLACE (addr.adr_street_number, '[^[:alpha:]]+', '')
END STREET_NUMBER_SUFFIX,
(SELECT SUBSTR (ptv_pty_code, 1, 3)
FROM prop_type_values
WHERE ptv_refno = pro.pro_hou_ptv_refno) HOUSE_TYPE
FROM properties pro,
(select adr_building,
adr_street_number
FROM addresses, address_usages
WHERE aus_adr_refno = adr_refno
AND aus_aut_far_code = 'PHYSICAL'
AND aus_aut_fao_code = 'PRO'
AND (aus_end_date IS NULL OR aus_end_date > SYSDATE)) addr
WHERE pro.pro_refno = aus_pro_refno
and pro_refno IN (select * from PIMSS_PROP_LIST_TEMP
UNION
select * from PIMSS_ASSOC_PROP_TEMP)
AND pro.pro_hou_hrv_hot_code IN (SELECT frv_code
FROM first_ref_values
WHERE frv_frd_domain IN ('ASS_OWN_REF')
AND frv_current_ind = 'Y');
You might possibly need an outer join if there's a chance that no rows could be returned from the addr subquery.

Related

Oracle: Value from main query is not available in subquery

I have this query, and one of its column is a subquery that should be bringing a list of values using a listagg function. This list has its starting point as the S.ID_ORGAO_INTELIGENCIA value. The list is a should be, it always has values.
The listagg function is consuming an inline view that uses a window function to create the list.
select *
from (
SELECT DISTINCT S.ID_SOLICITACAO,
S.NR_PROTOCOLO_SOLICITACAO,
S.DH_INCLUSAO,
S.ID_USUARIO,
U.NR_CPF,
OI.ID_MODULO,
OI.ID_ORGAO_INTELIGENCIA,
OI.NO_ORGAO_INTELIGENCIA,
R.ID_ATRIBUICAO,
P.ID_PERMISSAO,
1 AS TIPO_NOTIFICACAO,
(
select LISTAGG(oc6.ID_ORGAO_INTELIGENCIA || '-' || oc6.ord || '-', '; ') WITHIN GROUP (ORDER BY oc6.ord) eai
from (
SELECT oc1.ID_ORGAO_INTELIGENCIA,
oc1.ID_ORGAO_INTELIGENCIA_PAI,
oc1.SG_ORGAO_INTELIGENCIA,
rownum as ord
FROM TB_ORGAO_INTERNO oc1
WHERE oc1.DH_EXCLUSAO is null
-- THE VALUE FROM S.ID_ORGAO_INTELIGENCIA IS NOT AVAILBLE HERE
START WITH oc1.ID_ORGAO_INTELIGENCIA = S.ID_ORGAO_INTELIGENCIA
CONNECT BY prior oc1.ID_ORGAO_INTELIGENCIA_PAI = oc1.ID_ORGAO_INTELIGENCIA
) oc6) aproPrec
FROM TB_SOLICITACAO S
INNER JOIN TB_ORGAO_INTERNO OI ON S.ID_ORGAO_INTELIGENCIA = OI.ID_ORGAO_INTELIGENCIA
INNER JOIN TB_RELACIONAMENTO_ATRIBUICAO R
ON (R.ID_MODULO = OI.ID_MODULO AND R.ID_ORGAO_INTELIGENCIA IS NULL AND
R.ID_SOLICITACAO IS NULL)
INNER JOIN TB_PERMISSAO P
ON (P.ID_USUARIO = :usuario AND P.ID_ORGAO_INTELIGENCIA = :orgao AND
P.ID_ATRIBUICAO = R.ID_ATRIBUICAO)
INNER JOIN TB_USUARIO U ON (U.ID_USUARIO = S.ID_USUARIO)
WHERE 1 = 1
AND U.DH_EXCLUSAO IS NULL
AND P.DH_EXCLUSAO IS NULL
AND S.DH_EXCLUSAO IS NULL
AND OI.DH_EXCLUSAO IS NULL
AND R.ID_ATRIBUICAO IN :atribuicoes
AND P.ID_STATUS_PERMISSAO = 7
AND OI.ID_MODULO = 1
AND S.ID_STATUS_SOLICITACAO IN (1, 2, 5, 6)
and s.ID_ORGAO_INTELIGENCIA in (SELECT DISTINCT o.ID_ORGAO_INTELIGENCIA
FROM TB_ORGAO_INTERNO o
WHERE o.DH_EXCLUSAO IS NULL
START WITH o.ID_ORGAO_INTELIGENCIA = 3
CONNECT BY PRIOR o.ID_ORGAO_INTELIGENCIA = o.ID_ORGAO_INTELIGENCIA_PAI)
);
The problem is that the aproPrec column is always returning null as its result.
If I force the criteria to have the S.ID_ORGAO_INTELIGENCIA hardcoded, the list returns its true value.
If I chance this:
START WITH oc1.ID_ORGAO_INTELIGENCIA = S.ID_ORGAO_INTELIGENCIA
To this:
START WITH oc1.ID_ORGAO_INTELIGENCIA = 311
where 311 is the value that the S.ID_ORGAO_INTELIGENCIA column really has.
Is there a way to make this query works as 'I think' it should work?
To make it work, I changed the subquery by this another one:
(
select qt_.*
from (
SELECT QRY_NAME.*,
rownum as ord
FROM (
SELECT oc1.ID_ORGAO_INTELIGENCIA,
oc1.ID_ORGAO_INTELIGENCIA_PAI,
connect_by_root (oc1.ID_ORGAO_INTELIGENCIA) as root
FROM TB_ORGAO_INTERNO oc1
CONNECT BY NOCYCLE PRIOR oc1.ID_ORGAO_INTELIGENCIA_PAI = oc1.ID_ORGAO_INTELIGENCIA
) QRY_NAME
WHERE root = s.ID_ORGAO_INTELIGENCIA
) qt_
)

why SSRS asking to Define query parameters when already defined?

I have the below query which is working well in SQL. But when I use this query in ssrs(Visual studio 2015) it is giving me error saying define query parameters. I have already defined values for parametes but still getting the error. I feel something from the SQL query which s not getting supported in SSRS. Can anyone help?
[![SET FMTONLY OFF
USE GODSDB
declare
#start date = getdate() - 100
, #end date = getdate()
drop table #CallLog
declare #code varchar(max), #TableName varchar(max), #SeverName varchar(max)
--IF object_id('tempdb..#CallLog') IS NOT NULL DROP TABLE #CallLog
CREATE TABLE #CallLog (
\[JurisdictionShortIdentifier\] VARCHAR(100),
\[ContractCallLogOID\] INT,
\[ContractCallLogProcessQueueOID\] INT,
\[ContractOID\] INT,
\[CallDate\] DATETIME,
\[CallHandledBy\] VARCHAR(60),
\[CallLogOldGreenUnit\] INT,
\[CallLogNewGreenUnit\] INT,
\[Comment\] VARCHAR(7500)
)
set #TableName = '#CallLog'
set #SeverName = 'BA_GBASSTOCSISDB' -- sp_linkedservers
set #code = '
;with XMLNAMESPACES(DEFAULT ''http://tempuri.org/GEOUnit.xsd'')
select
ccl.JurisdictionShortIdentifier,
ccl.ContractCallLogOID,
que.ContractCallLogProcessQueueOID,
ccl.ContractOID,
ccl.db_insertDate as CallDate,
ccl.db_insertBy as CallHandledBy,
convert(xml, que.XMLString).value(''(/GEOUnit/GreenPowerUnits/GreenPowerUnitsOld)\[1\]'',''int'') as CallLogOldGreenUnit,
convert(xml, que.XMLString).value(''(/GEOUnit/GreenPowerUnits/GreenPowerUnitsNew)\[1\]'',''int'') as CallLogNewGreenUnit,
cmt.Comment
from CSISDB.dbo.ContractCallLog as ccl (nolock)
left join CSISDB.dbo.ContractCallLogProcessQueue as que (nolock) on ccl.ContractCallLogOID = que.ContractCallLogOID
left join CSISDB.dbo.Comment as cmt (nolock) on ccl.ContractCallLogOID = cmt.FKObjectOID and cmt.FKTableObjectOID = 1008
where 1 = 1
and ccl.ContractCallLogStatusIdentifier in (''GMOD'', ''GUS'', ''GI'')
and ccl.ContractCallLogReasonIdentifier in (''Changed'', ''GEOR'', ''NULL'', ''GEO'', ''GEO0'', ''GEO1'', ''GEO3'', ''GEO2'', ''CDR'', ''GEO4'', ''GEO5'', ''JUST GREEN adder'', ''JustGreen'')
--and ccl.JurisdictionShortIdentifier = ''AG''
and ccl.SourceSystemIdentifier = ''GBASS''
and ccl.db_insertDate between #start and #end
--and ccl.ContractCallLogOID = 57131879 --> TEST CASE
'
set #code = replace(#code, '#start', '''' + convert(varchar, convert(date, #start, 101)) + '''')
set #code = replace(#code, '#end', '''' + convert(varchar, convert(date, dateadd(day, 1, #end), 101)) + '''')
set #code = concat('insert into ', #TableName, ' select * from openquery (', #SeverName, ', ''' , replace(#code, '''', '''''') , ''')')
print #code
exec(#code)
-- select * from #CallLog where ContractCallLogOID = 57707501
-- some call log have multiple process queues, delete the process queues that don't is not modifying the geo units
delete a
from #CallLog as a
inner join #CallLog as b on a.ContractCallLogOID = b.ContractCallLogOID
and a.ContractCallLogProcessQueueOID != b.ContractCallLogProcessQueueOID
and a.CallLogNewGreenUnit is null
and b.CallLogNewGreenUnit is not null
--select * from #CallLog
select
ccl.JurisdictionShortIdentifier,
ccl.ContractCallLogOID,
ccl.ContractCallLogProcessQueueOID,
cnt.RtlrContractIdentifier,
ccl.ContractOID,
cst.ContractStatusIdentifier as ContractStatus,
ccl.CallLogOldGreenUnit,
ccl.CallLogNewGreenUnit,
cur.GreenLevelIndicator as CurrentGreenUnit,
cur.db_insertDate as GreenUnitLastUpdateDate,
cur.db_insertBy as GreenUnitLastUpdateBy,
ccl.CallDate,
ccl.CallHandledBy,
ccl.Comment
from #CallLog as ccl
inner join Contract as cnt (nolock) on ccl.ContractOID = cnt.ContractOID
and ccl.CallLogOldGreenUnit != ccl.CallLogNewGreenUnit
inner join ContractState as cst (nolock) on cnt.ContractOID = cst.ContractOID
left join ContractGreenContent as cur (nolock) on cnt.ContractOID = cur.ContractOID
and isnull(cur.EffectiveEndDate, dateadd(day, 1, getdate())) >= getdate()
left join ContractGreenContent as his (nolock) on cnt.ContractOID = his.ContractOID
and ccl.CallLogNewGreenUnit = his.GreenLevelIndicator
and his.db_insertDate between dateadd(day, -1, ccl.CallDate) and dateadd(day, 1, ccl.CallDate)
where his.ContractGreenContentOID is null
--select * from #CallLog
union all
select
ccl.JurisdictionShortIdentifier,
ccl.ContractCallLogOID,
ccl.ContractCallLogProcessQueueOID,
cnt.RtlrContractIdentifier,
ccl.ContractOID,
cst.ContractStatusIdentifier as ContractStatus,
ccl.CallLogOldGreenUnit,
ccl.CallLogNewGreenUnit,
cur.GreenLevelIndicator as CurrentGreenUnit,
cur.db_insertDate as GreenUnitLastUpdateDate,
cur.db_insertBy as GreenUnitLastUpdateBy,
ccl.CallDate,
ccl.CallHandledBy,
ccl.Comment
from #CallLog as ccl
inner join Contract as cnt (nolock) on ccl.ContractOID = cnt.ContractOID
and isnull(ccl.CallLogOldGreenUnit, 0) = isnull(ccl.CallLogNewGreenUnit, 0)
inner join ContractState as cst (nolock) on cnt.ContractOID = cst.ContractOID
left join ContractGreenContent as cur (nolock) on cnt.ContractOID = cur.ContractOID
and isnull(cur.EffectiveEndDate, dateadd(day, 1, getdate())) >= getdate()
SET FMTONLY ON][1]][1]
Make sure your parameter names and SQL variables are all spelled exactly the same, they are case sensitive.
Also try declaring each variable on it own line with its own DECLARE statement. I've seen this fix this issue 'sometimes'
Your parameters are inside your #SQL query variable. The server that you are running the OPENQUERY from doesn't recognize the parameters since they were declared on another server.
Put the parameter declarations inside your SQL variable:
set #code = '
declare
#start date = getdate() - 100
, #end date = getdate()
...

oracle SQL procedure error not ended properly

I am trying to select the total number of each value in column paxtype with the following letters m,f,i,c but my error is sql not ended properly
(select b.PAXTYPE from xxxx b, xxx a)
(case b.PAXTYPE
when 'M' then count('M')
when 'F' then count('F')
when 'I' then count('I')
when 'C' then count('C')
END)
where a.date_key=to_char(b.FLIGHTDATE,'RRRRMMDD')
and a.FLTNUM_KEY= trim(substr(b.flightnumber,3))
and a.origin=b.frm
and a.destination=b.too
--and a.date_key=20170801
--and fightnumber = '100'
and trim(a.cancelled) is null
and rownum = 1
)
Firstly You are not using the correct sql syntax. Also, there are several other problems with your query.
Table names should come after columns in select .
You need to use group by since you need count
There is no need for CASE block
why is ROWNUM = 1 required?
This query should work fine for your requirement.
SELECT b.PAXTYPE, COUNT (b.PAXTYPE)
FROM xxxx b, xxx a
WHERE a.date_key = TO_CHAR (b.FLIGHTDATE, 'RRRRMMDD')
AND a.FLTNUM_KEY = TRIM (SUBSTR (b.flightnumber, 3))
AND a.origin = b.frm
AND a.destination = b.too
--and a.date_key=20170801
--and fightnumber = '100'
AND TRIM (a.cancelled) IS NULL
--and rownum = 1 # Why was it required?
GROUP BY b.PAXTYPE;
Additionally, If you need only the counts for M,F,I,C then add AND b.PAXTYPE IN ('M','F','I','C') before group by

ORA-01427: Subquery returns more than one row

When I execute the query below, I get the message like this: "ORA-01427: Sub-query returns more than one row"
Define REN_RunDate = '20160219'
Define MOP_ADJ_RunDate = '20160219'
Define RID_RunDate = '20160219'
Define Mbr_Err_RunDate = '20160219'
Define Clm_Err_RunDate = '20160219'
Define EECD_RunDate = '20160219'
select t6.Member_ID, (Select 'Y' from MBR_ERR t7 where t7.Member_ID = t6.Member_ID and t7.Rundate = &Mbr_Err_RunDate ) Mbr_Err,
NVL(Claim_Sent_Amt,0) Sent_Claims, Rejected_Claims,Orphan_Claim_Amt,Claims_Accepted, MOP_Adj_Sent Sent_MOP_Adj,Net_Sent,
(Case
When Net_Sent < 45000 then 0
When Net_Sent > 25000 then 20500
Else
Net_Sent - 45000
End
)Net_Sent_RI,
' ' Spacer,
Total_Paid_Claims CMS_Paid_Claims, MOP_Adjustment CM_MOP_Adj, MOP_Adjusted_Paid_claims CM_Net_Claims, Estimated_RI_Payment CM_RI_Payment
from
(
select NVL(t3.Member_ID,t5.Member_ID)Member_ID, t3.Claim_Sent_Amt, NVL(t4.Reject_Claims_Amt,0) Rejected_Claims, NVL( t8.Orphan_Amt,0) Orphan_Claim_Amt,
(t3.Claim_Sent_Amt - NVL(t4.Reject_Claims_Amt,0) - NVL(t8.Orphan_Amt,0)) Claims_Accepted,
NVL(t2.MOP_Adj_Amt,0) MOP_Adj_Sent ,
( (t3.Claim_Sent_Amt - NVL(t4.Reject_Claims_Amt,0)) - NVL(t2.MOP_Adj_Amt,0) - NVL(t8.Orphan_Amt,0) ) Net_Sent,
t5.Member_ID CMS_Mbr_ID,t5.Total_Paid_Claims,t5.MOP_Adjustment, t5.MOP_Adjusted_Paid_Claims, t5.Estimated_RI_Payment
From
(
Select t1.Member_ID, Sum( t1.Paid_Amount) Claim_Sent_Amt
From RENS t1
where t1.rundate = &REN_RunDate
group by t1.Member_ID
) t3
Left Join MOP_ADJ t2
on (t3.Member_ID = t2.Member_ID and t2.rundate = &MOP_ADJ_RunDate)
Left Join
(select Member_ID, sum(Claim_Total_Paid_Amount) Reject_Claims_Amt from CLAIM_ERR
where Rundate = &Claim_Err_RunDate
and Claim_Total_Paid_Amount != 0
Group by member_ID
)t4
on (t4.Member_ID = t3.Member_ID )
Full Outer Join
(
select distinct Member_ID,Total_Paid_Claims,MOP_Adjustment,MOP_Adjusted_Paid_Claims, Estimated_RI_Payment
from RID
where Rundate = &RID_RunDate
and Estimated_RI_Payment != 0
)t5
On(t5.Member_ID = t3.Member_ID)
Left Outer Join
(
select Member_ID, Sum(Claim_Paid_Amount) Orphan_Amt
From EECD
where RunDate = &EECD_RunDate
group by Member_ID
)t8
On(t8.Member_ID = t3.Member_ID)
)t6
order by Member_ID
You have this expression among the select columns (at the top of your code):
(Select 'Y' from MBR_ERR t7 where t7.Member_ID = t6.Member_ID
and t7.Rundate = &Mbr_Err_RunDate ) Mbr_Err
If you want to select the literal 'Y', then just select 'Y' as Mbr_Err. If you want to select either 'Y' or null, depending on whether the the subquery returns exactly one row or zero rows, then write it that way.
I suspect this subquery (or perhaps another one in your code, used in a similar way) returns more than one row - in which case you will get exactly the error you got.

How to return all rows if IN clause has no value?

Following is sample query.
CREATE PROCEDURE GetModel
(
#brandids varchar(100), -- brandid="1,2,3"
#bodystyleid varchar(100) -- bodystyleid="1,2,3"
)
AS
select * from model
where brandid in (#brandids) -- use a UDF to return table for comma delimited string
and bodystyleid in (#bodystyleid)
My requirement is that if #brandids or #bodystyleid is blank, query should return all rows for that condition.
Please guide me how to do this? Also suggest how to write this query to optimize performance.
You'll need dynamic SQL or a split function for this anyway, since IN ('1,2,3') is not the same as IN (1,2,3).
Split function:
CREATE FUNCTION dbo.SplitInts
(
#List VARCHAR(MAX),
#Delimiter CHAR(1)
)
RETURNS TABLE
AS
RETURN ( SELECT Item = CONVERT(INT, Item) FROM (
SELECT Item = x.i.value('(./text())[1]', 'int') FROM (
SELECT [XML] = CONVERT(XML, '<i>' + REPLACE(#List, #Delimiter, '</i><i>')
+ '</i>').query('.') ) AS a CROSS APPLY [XML].nodes('i') AS x(i)) AS y
WHERE Item IS NOT NULL
);
Code becomes something like:
SELECT m.col1, m.col2 FROM dbo.model AS m
LEFT OUTER JOIN dbo.SplitInts(NULLIF(#brandids, ''), ',') AS br
ON m.brandid = COALESCE(br.Item, m.brandid)
LEFT OUTER JOIN dbo.SplitInts(NULLIF(#bodystyleid, ''), ',') AS bs
ON m.bodystyleid = COALESCE(bs.Item, m.bodystyleid)
WHERE (NULLIF(#brandids, '') IS NULL OR br.Item IS NOT NULL)
AND (NULLIF(#bodystyleid, '') IS NULL OR bs.Item IS NOT NULL);
(Note that I added a lot of NULLIF handling here... if these parameters don't have a value, you should be passing NULL, not "blank".)
Dynamic SQL, which will have much less chance of leading to bad plans due to parameter sniffing, would be:
DECLARE #sql NVARCHAR(MAX);
SET #sql = N'SELECT columns FROM dbo.model
WHERE 1 = 1 '
+ COALESCE(' AND brandid IN (' + #brandids + ')', '')
+ COALESCE(' AND bodystyleid IN (' + #bodystyleid + ')', '');
EXEC sp_executesql #sql;
Of course as #JamieCee points out, dynamic SQL could be vulnerable to injection, as you'll discover if you search for dynamic SQL anywhere. So if you don't trust your input, you'll want to guard against potential injection attacks. Just like you would if you were assembling ad hoc SQL inside your application code.
When you move to SQL Server 2008 or better, you should look at table-valued parameters (example here).
if(#brandids = '' or #brandids is null)
Begin
Set #brandids = 'brandid'
End
if(#bodystyleid = '' or #bodystyleid is null)
Begin
Set #bodystyleid = 'bodystyleid'
End
Exec('select * from model where brandid in (' + #brandids + ')
and bodystyleid in (' + #bodystyleid + ')')

Resources