Performance query in sql
This query takes 1 mins to execute, Please suggesr if we can improve more on performance
SELECT P.ProgramId
,P.Tier4Id
,7 AS MetricId
,(convert(DATETIME, CONVERT(VARCHAR, Month(s.DATE)) + '/1/' + CONVERT(VARCHAR, Year(s.DATE)))) AS DATE
,CASE
WHEN SUM(ISNULL(S.ITD_BCWS_PMB, 0)) <> 0
THEN ROUND(SUM(ISNULL(S.ITD_BCWP_PMB, 0)) / SUM(ISNULL(S.ITD_BCWS_PMB, 0)), 2)
ELSE NULL
END AS Value
,SUM(ISNULL(S.ITD_BCWP_PMB, 0)) AS BCWP
FROM Staging.SPI_CPI_WBS S
INNER JOIN Core.Projects PJ ON S.ProjectId = PJ.ProjectId AND PJ.IsActive = 1
INNER JOIN Core.ProgramFinancials PF ON PF.ProgramId = S.ProgramId AND Year(PF.DATE) = Year(S.DATE) AND PF.IsYearly = 1
INNER JOIN Core.v_WBS_Tier_Structure_SPICPI P ON S.WBSId = P.WBSId AND P.ProgramId = S.ProgramId
WHERE S.LSKINdicator = 1 AND S.ProjectId IS NOT NULL
/*AP3-820 Check for BCWP > 0*/
AND ISNULL(S.ITD_BCWP_PMB, 0) > 0 AND (P.ProgramStatus = 1 OR isnull(PF.Spend, 0) != 0)
GROUP BY P.ProgramId
,s.DATE
,P.Tier4Id
HAVING SUM(ISNULL(S.ITD_BCWP_PMB, 0)) > 0
Smash126
Hi This entire query i am posting see if any more optimization can be done please
UPDATE DW.ProgramScores_T4_P
SET
SPI=null
,SPI_H=null
,CPI=null
,CPI_h=null
, M_SPI = null
,M_SPI_H = null
,M_CPI = null
,M_CPI_H = null
where Date between dateadd(mm,-12,getdate()) and getdate()
-- SPI CPI - Programscores
MERGE DW.ProgramScores_T4_P DW
USING
SELECT isnull(SPI.ProgramId, CPI.ProgramId) AS ProgramId
,isnull(SPI.DATE, CPI.DATE) AS DATE
,isnull(SPI.Tier4Id,CPI.Tier4Id) as Tier4Id
,SPI
,SPI_H
,CPI
,CPI_H
,CASE
WHEN isnull(SPI.DATE, CPI.DATE) BETWEEN dateadd(mm, - 12, getdate()) AND getdate()
THEN 1
ELSE 0
END AS Datediff
,Month(isnull(SPI.DATE, CPI.DATE)) AS Month
,Year(isnull(SPI.DATE, CPI.DATE)) AS Year
FROM (
SELECT SPI.ProgramId
,SPI.Metricid
,Tier4Id
,DATE
,SPI
,SPI_H
FROM (
SELECT ProgramId
,Tier4Id
,A.MetricId
,DATE
,Value AS SPI
CASE
WHEN [Value] IS NULL OR [IsGoalOriented] = (0) OR [IsGoalOriented] IS NULL /*OR MBM.fn_CheckGoalsAvailability(A.MetricId) = 0 */
THEN (5)
ELSE CASE
WHEN [Value] >= [LCLG] AND [Value] <= [UCLG] OR [Value] >= [LCLG] AND [UCLG] IS NULL
THEN (2)
ELSE CASE
WHEN [Value] >= [LCLY] AND [Value] <= [UCLY]
THEN (3)
ELSE (4)
END
END
END
) AS SPI_H
FROM (
SELECT P.ProgramId
,P.Tier4Id
,7 AS MetricId
,(convert(DATETIME, CONVERT(VARCHAR, Month(s.DATE)) + '/1/' + CONVERT(VARCHAR, Year(s.DATE)))) AS DATE
,CASE
WHEN SUM(ISNULL(S.ITD_BCWS_PMB, 0)) <> 0
THEN ROUND(SUM(ISNULL(S.ITD_BCWP_PMB, 0)) / SUM(ISNULL(S.ITD_BCWS_PMB, 0)), 2)
ELSE NULL
END AS Value
,SUM(ISNULL(S.ITD_BCWP_PMB, 0)) AS BCWP
FROM Staging.SPI_CPI_WBS S
INNER JOIN Core.Projects PJ ON S.ProjectId = PJ.ProjectId AND PJ.IsActive = 1
INNER JOIN Core.ProgramFinancials PF ON PF.ProgramId = S.ProgramId AND Year(PF.DATE) = Year(S.DATE) AND PF.IsYearly = 1
INNER JOIN Core.v_WBS_Tier_Structure_SPICPI P ON S.WBSId = P.WBSId AND P.ProgramId = S.ProgramId
WHERE S.LSKINdicator = 1 AND S.ProjectId IS NOT NULL
/*AP3-820 Check for BCWP > 0*/
AND ISNULL(S.ITD_BCWP_PMB, 0) > 0 AND (P.ProgramStatus = 1 OR isnull(PF.Spend, 0) != 0)
GROUP BY P.ProgramId
,s.DATE
,P.Tier4Id
HAVING SUM(ISNULL(S.ITD_BCWP_PMB, 0)) > 0
) A
INNER JOIN MBM.Metrics M ON M.MetricId = A.MetricId AND M.IsActive = 1
) SPI
) SPI
LEFT JOIN (
SELECT CPI.ProgramId
--,WBSId
,Tier4Id
--,Tier3Id
--,Tier2Id
,CPI.Metricid
,DATE
,CPI
,CPI_H
FROM (
SELECT ProgramId
--,WBSId
,Tier4Id
--,Tier3Id
--,Tier2Id
,A.MetricId
,DATE
,Value AS CPI
CASE
WHEN [Value] IS NULL OR [IsGoalOriented] = (0) OR [IsGoalOriented] IS NULL /*OR MBM.fn_CheckGoalsAvailability(A.MetricId) = 0 */
THEN (5)
ELSE CASE
WHEN [Value] >= [LCLG] AND [Value] <= [UCLG] OR [Value] >= [LCLG] AND [UCLG] IS NULL
THEN (2)
ELSE CASE
WHEN [Value] >= [LCLY] AND [Value] <= [UCLY] THEN (3)
ELSE (4)
END
END
END
) AS CPI_H
FROM (
SELECT P.ProgramId
--,S.WBSId
,P.Tier4Id
--,WBS.Tier3Id
--,WBS.Tier2Id
,8 AS MetricId
,(convert(DATETIME, CONVERT(VARCHAR, Month(s.DATE)) + '/1/' + CONVERT(VARCHAR, Year(s.DATE)))) AS DATE
,CASE
WHEN SUM(ISNULL(S.ITD_ACWP, 0)) <> 0
THEN ROUND(SUM(ISNULL(S.ITD_BCWP_PMB, 0)) / SUM(ISNULL(S.ITD_ACWP, 0)), 2)
ELSE NULL
END AS Value
,SUM(ISNULL(S.ITD_BCWP_PMB, 0)) AS BCWP
FROM Staging.SPI_CPI_WBS S
INNER JOIN Core.Projects PJ ON S.ProjectId = PJ.ProjectId AND PJ.IsActive = 1
--INNER JOIN Core.Programs P ON P.ProgramId = S.ProgramId and P.Isactive=1
INNER JOIN Core.ProgramFinancials PF ON PF.ProgramId = S.ProgramId AND Year(PF.DATE) = Year(S.DATE) AND PF.IsYearly = 1
--inner join Core.WBS_CAM_TIERS_Structure WBS ON S.WBSId = WBS.WBSId
INNER JOIN Core.v_WBS_Tier_Structure_SPICPI P ON S.WBSId = P.WBSId AND P.ProgramId = S.ProgramId
WHERE S.LSKINdicator = 1 AND S.ProjectId IS NOT NULL
/*AP3-820 Check for BCWP > 0*/
AND ISNULL(S.ITD_BCWP_PMB, 0) > 0 AND (P.ProgramStatus = 1 OR isnull(PF.Spend, 0) != 0)
GROUP BY P.ProgramId
,s.DATE
--,S.WBSId
,P.Tier4Id
--,WBS.Tier3Id
--,WBS.Tier2Id
HAVING SUM(ISNULL(S.ITD_BCWP_PMB, 0)) > 0 /*AP3-688 & AP3-702 Check for BCWP > 0 */
) A
INNER JOIN MBM.Metrics M ON M.MetricId = A.MetricId AND M.IsActive = 1
) CPI
WHERE CPI IS NOT NULL
) CPI
ON CPI.ProgramId = SPI.ProgramId AND CPI.DATE = SPI.DATE AND
CPI.Tier4Id = SPI.Tier4Id --AND CPI.Tier3Id = SPI.Tier3Id AND CPI.Tier2Id = SPI.Tier2Id
)SPICPI
on SPICPI.ProgramId = DW.ProgramId and Datediff(dd,SPICPI.Date,DW.Date) = 0 and
SPICPI.Tier4Id = DW.Tier4Id --and SPICPI.Tier3Id = DW.Tier3Id and SPICPI.Tier2Id = DW.Tier2Id
WHEN MATCHED AND (SPICPI.Datediff = 1) THEN
update SET DW.SPI = SPICPI.SPI,
DW.SPI_H = SPICPI.SPI_H,
DW.CPI = SPICPI.CPI,
DW.CPI_H = SPICPI.CPI_H,
DW.UpdatedDate = getdate()
WHEN NOT MATCHED THEN
insert (ProgramId,Tier4Id, Date,SPI,SPI_H,CPI,CPI_H,CreatedDate)
values(SPICPI.ProgramId,SPICPI.Tier4Id,SPICPI.Date,SPICPI.SPI,SPICPI.SPI_H, SPICPI.CPI,SPICPI.CPI_H,getdate());
Smash126
Similar Messages
-
Need help in improving the performance for the sql query
Thanks in advance for helping me.
I was trying to improve the performance of the below query. I tried the following methods used merge instead of update, used bulk collect / Forall update, used ordered hint, created a temp table and upadated the target table using the same. The methods which I used did not improve any performance. The data count which is updated in the target table is 2 million records and the target table has 15 million records.
Any suggestions or solutions for improving performance are appreciated
SQL query:
update targettable tt
set mnop = 'G',
where ( x,y,z ) in
select a.x, a.y,a.z
from table1 a
where (a.x, a.y,a.z) not in (
select b.x,b.y,b.z
from table2 b
where 'O' = b.defg
and mnop = 'P'
and hijkl = 'UVW';987981 wrote:
I was trying to improve the performance of the below query. I tried the following methods used merge instead of update, used bulk collect / Forall update, used ordered hint, created a temp table and upadated the target table using the same. The methods which I used did not improve any performance. And that meant what? Surely if you spend all that time and effort to try various approaches, it should mean something? Failures are as important teachers as successes. You need to learn from failures too. :-)
The data count which is updated in the target table is 2 million records and the target table has 15 million records.Tables have rows btw, not records. Database people tend to get upset when rows are called records, as records exist in files and a database is not a mere collection of records and files.
The failure to find a single faster method with the approaches you tried, points to that you do not know what the actual performance problem is. And without knowing the problem, you still went ahead, guns blazing.
The very first step in dealing with any software engineering problem, is to identify the problem. Seeing the symptoms (slow performance) is still a long way from problem identification.
Part of identifying the performance problem, is understanding the workload. Just what does the code task the database to do?
From your comments, it needs to find 2 million rows from 15 million rows. Change these rows. And then write 2 million rows back to disk.
That is not a small workload. Simple example. Let's say that the 2 million row find is 1ms/row and the 2 million row write is also 1ms/row. This means a 66 minute workload. Due to the number of rows, an increase in time/row either way, will potentially have 2 million fold impact.
So where is the performance problem? Time spend finding the 2 million rows (where other tables need to be read, indexes used, etc)? Time spend writing the 2 million rows (where triggers and indexes need to be fired and maintained)? Both? -
SQL query (pl/sql function body returning query) performance issue
I create my report in building my sql instruction with ( SQL Query pl/sql function body returning sql query );
My report take more than 20 seconds however if i did a cut and paste with the sql code in TOAD the same sql take 1 second.
To try to discover the source of the problem; i take the sql generated by the function and i create another report ( sql query ) this new report take 2 seconds.
My query is very big 25,000 characters with database link.
What is the difference between SQL-quey and sql-query(pl/sql function body returning sql query)
Thanks
MarcMarc,
Firstly...don't compare the timings from Toad, since often Toad only fetches the first few records for you (i.e. it pages them).
Secondly....the database link could be a factor here, but without seeing your query it's too hard to say.
Can you post the query somewhere (on a webserver say)? -
We have to inverstigate about a reporting solution where things are getting slow (may be material, database design, network matters).
I have red a lot in MSDN and some books about performance tuning on SQL Server 2008 R2 (or other) but frankly, I feel a little lost in all that stuff
I'am looking for practical steps in order to do the tuning. Someone had like a recipe for that : a success story...
My (brain storm) Methodology should follow these steps:
Resource bottlenecks: CPU, memory, and I/O bottlenecks
tempdb bottlenecks
A slow-running user query : Missing indexes, statistics,...
Use performance counters : there are many, can one give us the list of the most important
how to do fine tuning about SQL Server configuration
SSRS, SSIS configuration ?
And do the recommandations.
Thanks
"there is no Royal Road to Mathematics, in other words, that I have only a very small head and must live with it..."
Edsger W. DijkstraHello,
There is no clear defined step which can be categorized as step by step to performance tuning.Your first goal is to find out cause or drill down to factor causing slowness of SQL server it can be poorly written query ,missing indexes,outdated stats.RAM crunch
CPU crunch so on and so forth.
I generally refer to below doc for SQL server tuning
http://technet.microsoft.com/en-us/library/dd672789(v=sql.100).aspx
For SSIS tuning i refer below doc.
http://technet.microsoft.com/library/Cc966529#ECAA
http://msdn.microsoft.com/en-us/library/ms137622(v=sql.105).aspx
When I face issue i generally look at wait stats ,wait stats give you idea about on what resource query was waiting.
--By Jonathan KehayiasSELECT TOP 10
wait_type ,
max_wait_time_ms wait_time_ms ,
signal_wait_time_ms ,
wait_time_ms - signal_wait_time_ms AS resource_wait_time_ms ,
100.0 * wait_time_ms / SUM(wait_time_ms) OVER ( )
AS percent_total_waits ,
100.0 * signal_wait_time_ms / SUM(signal_wait_time_ms) OVER ( )
AS percent_total_signal_waits ,
100.0 * ( wait_time_ms - signal_wait_time_ms )
/ SUM(wait_time_ms) OVER ( ) AS percent_total_resource_waits
FROM sys.dm_os_wait_stats
WHERE wait_time_ms > 0 -- remove zero wait_time
AND wait_type NOT IN -- filter out additional irrelevant waits
( 'SLEEP_TASK', 'BROKER_TASK_STOP', 'BROKER_TO_FLUSH',
'SQLTRACE_BUFFER_FLUSH','CLR_AUTO_EVENT', 'CLR_MANUAL_EVENT',
'LAZYWRITER_SLEEP', 'SLEEP_SYSTEMTASK', 'SLEEP_BPOOL_FLUSH',
'BROKER_EVENTHANDLER', 'XE_DISPATCHER_WAIT', 'FT_IFTSHC_MUTEX',
'CHECKPOINT_QUEUE', 'FT_IFTS_SCHEDULER_IDLE_WAIT',
'BROKER_TRANSMITTER', 'FT_IFTSHC_MUTEX', 'KSOURCE_WAKEUP',
'LAZYWRITER_SLEEP', 'LOGMGR_QUEUE', 'ONDEMAND_TASK_QUEUE',
'REQUEST_FOR_DEADLOCK_SEARCH', 'XE_TIMER_EVENT', 'BAD_PAGE_PROCESS',
'DBMIRROR_EVENTS_QUEUE', 'BROKER_RECEIVE_WAITFOR',
'PREEMPTIVE_OS_GETPROCADDRESS', 'PREEMPTIVE_OS_AUTHENTICATIONOPS',
'WAITFOR', 'DISPATCHER_QUEUE_SEMAPHORE', 'XE_DISPATCHER_JOIN',
'RESOURCE_QUEUE' )
ORDER BY wait_time_ms DESC
use below link to analyze wait stats
http://www.sqlskills.com/blogs/paul/wait-statistics-or-please-tell-me-where-it-hurts/
HTH
PS: for reporting services you can post in SSRS forum
Please mark this reply as the answer or vote as helpful, as appropriate, to make it useful for other readers -
Is this the best performed query?
Hi Guys,
Is this the best performed query or i can still improve it ?
I am new to SQL performacne tune, please help to get best performance of the query.
SQL> EXPLAIN PLAN SET STATEMENT_ID = 'ASH'
2 FOR
3 SELECT /*+ FIRST_ROWS(30) */ PSP.PatientNumber, PSP.IntakeID, U.OperationCenterCode OpCenterProcessed,
4 PSP.ServiceCode, PSP.UOMcode, PSP.StartDt, PSP.ProvID, PSP.ExpDt, NVL(PSP.Units, 0) Units,
5 PAS.Descript, PAS.ServiceCatID, PSP.CreatedBy AuthCreatedBy, PSP.CreatedDateTime AuthCreatedDateTime,
6 PSP.AuthorizationID, PSP.ExtracontractReasonCode, PAS.ServiceTypeCode,
7 NVL(PSP.ProvNotToExceedRate, 0) ProvOverrideRate,
8 prov.ShortName ProvShortName, PSP.OverrideReasonCode, PAS.ContractProdClassId
9 ,prov.ProvParentID ProvParentID, prov.ProvTypeCd ProvTypeCd
10 FROM tblPatServProv psp, tblProductsAndSvcs pas, tblProv prov, tblUser u, tblGlMonthlyClose GLMC
11 WHERE GLMC.AUTHORIZATIONID >= 239
12 AND GLMC.AUTHORIZATIONID < 11039696
13 AND PSP.AuthorizationID = GLMC.AUTHORIZATIONID
14 AND PSP.Authorizationid < 11039696
15 AND (PSP.ExpDt >= to_date('01/03/2000','MM/DD/YYYY') OR PSP.ExpDt IS NULL)
16 AND PSP.ServiceCode = PAS.ServiceCode(+)
17 AND prov.ProvID(+) = PSP.ProvID
18* AND U.UserId(+) = PSP.CreatedBy
19 /
Explained.
Elapsed: 00:00:00.46
SQL> SELECT * FROM TABLE(dbms_xplan.display);
Plan hash value: 3602678330
| Id | Operation | Name | Rows | Bytes | Cost (%CPU)| Time |
| 0 | SELECT STATEMENT | | 8503K| 3073M| 91 (2)| 00:00:02 |
|* 1 | HASH JOIN RIGHT OUTER | | 8503K| 3073M| 91 (2)| 00:00:02 |
| 2 | TABLE ACCESS FULL | TBLPRODUCTSANDSVCS | 4051 | 209K| 16 (0)| 00:00:01 |
| 3 | NESTED LOOPS | | 31 | 6200 | 75 (2)| 00:00:01 |
| 4 | NESTED LOOPS OUTER | | 30 | 5820 | 45 (3)| 00:00:01 |
|* 5 | HASH JOIN RIGHT OUTER | | 30 | 4950 | 15 (7)| 00:00:01 |
| 6 | TABLE ACCESS FULL | TBLUSER | 3444 | 58548 | 12 (0)| 00:00:01 |
|* 7 | TABLE ACCESS FULL | TBLPATSERVPROV | 8301K| 585M| 2 (0)| 00:00:01 |
| 8 | TABLE ACCESS BY INDEX ROWID| TBLPROV | 1 | 29 | 1 (0)| 00:00:01 |
|* 9 | INDEX UNIQUE SCAN | PK_TBLPROV | 1 | | 0 (0)| 00:00:01 |
|* 10 | INDEX UNIQUE SCAN | PK_W_GLMONTHLYCLOSE | 1 | 6 | 1 (0)| 00:00:01 |
Predicate Information (identified by operation id):
1 - access("PSP"."SERVICECODE"="PAS"."SERVICECODE"(+))
5 - access("U"."USERID"(+)="PSP"."CREATEDBY")
7 - filter(("PSP"."EXPDT">=TO_DATE('2000-01-03 00:00:00', 'yyyy-mm-dd hh24:mi:ss') OR
"PSP"."EXPDT" IS NULL) AND "PSP"."AUTHORIZATIONID">=239 AND "PSP"."AUTHORIZATIONID"<11039696)
9 - access("PROV"."PROVID"(+)="PSP"."PROVID")
10 - access("PSP"."AUTHORIZATIONID"="GLMC"."AUTHORIZATIONID")
filter("GLMC"."AUTHORIZATIONID">=239 AND "GLMC"."AUTHORIZATIONID"<11039696)
28 rows selected.
Elapsed: 00:00:00.42Thanks a lot for your reply.
Here are the indexes on those tables.
table --> TBLPATSERVPROV ---> index PK_TBLPATSERVPROV ---> column AUTHORIZATIONID
table --> TBLPRODUCTSANDSVCS ---> index PK_TBLPRODUCTSANDSVCS ---> column SERVICECODE
table --> TBLUSER ---> index PK_TBLUSER ---> column USERID -
Frm-40505:ORACLE error: unable to perform query in oracle forms 10g
Hi,
I get error frm-40505:ORACLE error: unable to perform query on oracle form in 10g environment, but the same form works properly in 6i.
Please let me know what do i need to do to correct this problem.
Regards,
PriyaHi everyone,
I have block created on view V_LE_USID_1L (which gives the error frm-40505) . We don't need any updation on this block, so the property 'updateallowed' is set to 'NO'.
To fix this error I modified 'Keymode' property, set it to 'updatable' from 'automatic'. This change solved the problem with frm-40505 but it leads one more problem.
The datablock v_le_usid_1l allows user to enter the text (i.e. updated the field), when the data is saved, no message is shown. When the data is refreshed on the screen, the change done previously on the block will not be seen (this is because the block updateallowed is set to NO), how do we stop the fields of the block being editable?
We don't want to go ahead with this solution as, we might find several similar screens nad its diff to modify each one of them individually. When they work properly in 6i, what it doesn't in 10g? does it require any registry setting?
Regards,
Priya -
Different output of same query in SQL Server and Oracle
I have two tables table1 and table2
--table1 has two columns c1 int and c2 varchar. there are not constraints added in it. it has data as given below
c1 c2
6 d
5 j
102 g
4 g
103 f
3 h
501 j
1 g
601 n
2 m
--table2 has only one column c1 int. there are not constraints added in it. it has data as given below
c1
6
1
4
3
2
now when i run below given query in sql server and oracle it gives me different result
select *
from table1
inner join (SELECT ROW_NUMBER() OVER (order by c1 ASC) AS c1 from table2) table2 on table2.c1=table1.c1
sql server output
c1 c2 c1
1 g 1
2 m 2
3 h 3
4 g 4
5 j 5
oracle output
C1 C2 C1
5 j 5
4 g 4
3 h 3
1 g 1
2 m 2
If you notice the first column in both output. It is sorted in sql server and not in oracle.
Why it is behaving differently in oracle? Is there any way I can solve this in oracle?
Thanks,
JigsIt is NOT behaving "differently" in Oracle; you just haven't specified an order that you expect your results to be in, so you're going to get output in whatever order the database fancies displaying it (ie. no guarenteed order). This is an artifact of how the database chooses to put together the data, and different databases (or even datasets within the same database) can and most likely will behave differently.
Even SQL Server won't guarentee to always get your data in an ordered fashion if you exclude the order by clause, even if you think it has always output the data in an ordered fashion.
Your solution is to add an order by clause, in BOTH databases, to force the order of the output data. -
SQL Query (pl/sql function body returning Sql query)
Hi All,
I have created a region of "SQL Query (pl/sql function body returning Sql query)" type and it is working fine , but when I am migrating(export /import) this application from development to systest environment ,
It gives error for this region :
Error ERR-1101 Unable to process function body returning query.
OK
ORA-06550: line 1, column 52: PLS-00306: wrong number or types of arguments in call to 'FU_TRADE_REPORT_QUERY' ORA-06550: line 1, column 45: PL/SQL: Statement ignored
Any pointer ...why this is happening.
Thanks
DikshitIf your function is a stored function that is called from within APEX (function body not coded into the app itself), have you made sure that the function has been created and compiles ok prior to installing your apex app.
If there are some dependency issues between other PL/SQL units or database objects that are causing your function not to be compiled, you apex install will fail as you are trying to reference an uncompelled bit of pl/sql.
Let me know how you get on
Regards
Duncan -
SQL Query(PL/SQL Function Returning SQL Query)
I am trying to write a dynamic report using SQL Query(PL/SQL Function Returning SQL Query).
I can get the report to run but I need to concatinate some columns into one, seperated by a comma or a dash.
I have tried select *****||','||***** alias
also select *****||'-'||***** alias
but I always get an error.
Is there a way of doing this please
GusThis is my full query
declare
v_query varchar2(4000);
begin
if :P63_TRAN_INFO = 2 THEN
v_query := 'select
A.FILENR,
A.EXERCISENAME,
A.STARTDATE,
A.ENDDATE,
A.UNIT,
A.ACCADDRESSES, B.ADDRESS, B.ADDRESS_1, B.POST_CODE, B.TOWN,
A.EXERCISEAREAS,
A.TOTALVEHICLES,
A.TOTALTROOPS+A.RNTOTALTROOPS+A.RAFTOTALTROOPS TOTALTROOPS,
A.CAR, A.MINIBUS, A.HGV,
A.NAMERANK, A.ADDRESS, A.ADDRESSI, A.ADDRESSII, A.POSTCODE,
A.TRANSIT,
A.INFOONLY
from BFLOG_AT A, BFLOG_ACCADDRESS B
WHERE A.ACCADDRESSES = B.NAME
AND A.STARTDATE >= :P63_START_DATE
AND A.ENDDATE <= :P63_END_DATE
AND A.AUTHORISED = 1
AND A.INFOONLY = 1' ;
END IF;
RETURN v_query;
END;
This query runs ok, but if I try changing it to the code below with fields concatinated, then it fails
declare
v_query varchar2(4000);
begin
if :P63_TRAN_INFO = 2 THEN
v_query := 'select
A.FILENR,
A.EXERCISENAME,
A.STARTDATE,
A.ENDDATE,
A.UNIT,
A.ACCADDRESSES||','||B.ADDRESS||','||B.ADDRESS_1||','||B.POST_CODE||','||B.TOWN ADDRESS,
A.EXERCISEAREAS,
A.TOTALVEHICLES,
A.TOTALTROOPS+A.RNTOTALTROOPS+A.RAFTOTALTROOPS TOTALTROOPS,
A.CAR, A.MINIBUS, A.HGV,
A.NAMERANK, A.ADDRESS, A.ADDRESSI, A.ADDRESSII, A.POSTCODE,
A.TRANSIT,
A.INFOONLY
from BFLOG_AT A, BFLOG_ACCADDRESS B
WHERE A.ACCADDRESSES = B.NAME
AND A.STARTDATE >= :P63_START_DATE
AND A.ENDDATE <= :P63_END_DATE
--AND (A.EXERCISEAREAS LIKE "GAP, OA, OAL")
--OR (A.EXERCISEAREAS LIKE "Harz")
AND A.AUTHORISED = 1
AND A.INFOONLY = 1' ;
END IF;
RETURN v_query;
END;
Cheers
Gus -
SQL Query ( PL/SQL function body returning query ) page
Hello Friends,
I have a page with type SQL Query ( PL/SQL function body returning query ).
I have written a pl/sql block that returns a sql query - select statment.
Some times i am getting no data found error - does it got to do with the variable that stores the query .
=======================
ORA-06502: PL/SQL: numeric or value error: character string buffer too small
Error ERR-1101 Unable to process function body returning query.
OK
=====================
When the query is returned with records where exactly the records are stored is it in the variable declared in pl/sql block or with the Oracle Apex implicit cursor.
Here's the pl/sql block ..
The query is generated while the user is navigating through pages ..
====================
declare
l_return_stmt varchar2(32767);
l_select varchar2(32000);
l_from varchar2(32000);
l_where varchar2(32000);
l_order_by varchar2(32000);
l_stmt_recordcount varchar2(32000);
l_recordcount number ;
begin
l_select := 'select '||:P10_VARLIST1||:P10_VARLIST2||:P10_VARLIST3
||:P10_VARLIST4||:P10_VARLIST5;
l_from := ' from '||:P10_RELATION;
if length(:P10_WHERE) > 0 then
l_where := ' where '||:P10_WHERE;
else
l_where := '';
end if;
if length(:P10_ORDER_BY) > 0 then
l_order_by := ' order by '||:P10_ORDER_BY;
else
l_order_by := '';
end if;
l_return_stmt := l_select||l_from||l_where||l_order_by;
:P10_STMT := l_return_stmt;
return l_return_stmt;
end;
=============================
Appreciate your help in this regard.
thanks/kumar
Edited by: kumar73 on Apr 22, 2010 6:38 AMIt looks like the query string you are trying to pass back exceeds the 32K limit for a varchar. Where this is happening is kind of difficult to tell as it could be any number of points, and also depends on what you are passing into the process via page items.
I would first try to establish what combination of page items causes this error to occur. Then, starting from the bottom and working your way backwards, I would start 'switching off' some of the items you use to build your query until it breaks again, thus establishing which part is leading to the error.
Also, I'm not sure what :P10_STMT is doing (are you maybe using this for visiblity of the query created)?
It looks like the query string you are trying to pass back exceeds the 32K limit for a varchar. Where this is happening is kind of difficult to tell as it could be any number of points, and also depends on what you are passing into the process via page items.
I would first try to establish what combination of page items causes this error to occur. then, starting from the bottom and working your way backwards, I would start 'switching off' some of the items you use to build your query until it breaks again, thus establishing which part is leading to the error.
Also, I'm not sure what :P10_STMT is doing (are you maybe using this for visiblity of the query created)? -
SQL Query (PL/SQL function body returning SQL query) when using to_char
we are trying to build a report page of Type SQL Query (PL/SQL function body returning SQL query).
our query is so simple, we need to extract the month from the recording_date column.
declare
l_query varchar2(1000);
begin
l_query:='select to_char(recording_date,'MM')from re_productive';
return l_query;
end;
but we are having the following problem for this query
Function returning SQL query: Query cannot be parsed within the Builder. If you believe your query is syntactically correct, check the generic columns checkbox below the region source to proceed without parsing.
(ORA-06550: line 4, column 42: PLS-00103: Encountered the symbol "MON" when expecting one of the following: . ( * @ % & = - + ; < / > at in is mod remainder not rem <> or != or ~= >= <= <> and or like between || multiset member SUBMULTISET_ The symbol ". was inserted before "MON" to continue.)
Notes:
1-the query is correct and it was tested under Toad and SQL Plus.
2- we tried Use Generic Column Names (parse query at runtime only) option but we get the same problem.
any quick help please.Hi
You haven't escaped your quotes in the string. Try this...
DECLARE
l_query VARCHAR2(32767);
BEGIN
l_query:= 'select to_char(recording_date,''MM'') from re_productive';
RETURN l_query;
END;Cheers
Ben -
SQL Query (PL/SQL Function Body returning SQL query) doesn't return any row
I have a region with the following type:
SQL Query (PL/SQL Function Body returning SQL query).
In a search screen the users can enter different numbers, separated by an ENTER.
I want to check these numbers by replacing the ENTER, which is CHR(13) || CHR(10) I believe, with commas. And then I can use it like this: POD IN (<<text>>).
It's something like this:
If (:P30_POD Is Not Null) Then
v_where := v_where || v_condition || 'POD IN (''''''''||REPLACE(''' || :P30_POD || ''', CHR(13) || CHR(10), '','')||'''''''''')';
v_condition := ' AND ';
End If;
But the query doesn't return any rows.
I tried to reproduce it in Toad:
select * from asx_worklistitem
where
POD IN (''''||REPLACE('541449200000171813'||CHR(13) || CHR(10)||'541449206006341366', CHR(13) || CHR(10), ''',''')||'''')
==> This is the query that does't return any rows
select (''''||REPLACE('541449200000171813'||CHR(13) || CHR(10)||'541449206006341366', CHR(13) || CHR(10), ''',''')||'''')
from dual;
==> This returns '541449200000171813','541449206006341366'
select * from asx_worklistitem
where pod in ('541449200000171813','541449206006341366');
==> and when I copy/paste this in the above query, it does return my rows.
So why does my first query doesn't work?
Doe anyone have any idea?
Kind regards,
Geert
Message was edited by:
ZorryThanks for the help.
I made it work, but via the following code:
If (:P30_POD Is Not Null) Then
v_pods := REPLACE(:P30_POD, CHR(13) || CHR(10));
v_where := v_where || v_condition || 'POD IN (';
v_counter := 1;
WHILE (v_counter < LENGTH(v_pods)) LOOP
v_pod := SUBSTR(v_pods, v_counter, 18);
IF (v_counter <> 1) THEN
v_where := v_where || ',';
END IF;
v_where := v_where || '''' || v_pod || '''';
v_counter := v_counter + 18;
END LOOP;
v_where := v_where || ')';
v_condition := ' AND ';
End If;But now I want to make an update of all the records that correspond to this search criteria. I can give in a status via a dropdownlist and that I want to update all the records that correspond to one of these POD's with that status.
For a region you can build an SQL query via PL/SQL, but for a process you only have a PL/SQL block. Is the only way to update all these records by making a loop and make an update for every POD that is specified.
Because I think this will have a lot of overhead.
I would like to make something like a multi row update in an updateable report, but I want to specify the status from somewhere else. Is this possible? -
How to get exact query of sql in oracle?
Hi all,
Hope doing well,
sir i was using one query of sql that is here:
Declare @nshiftmax datetime
set @nshiftmax=convert(time,DATEADD(N,1439,0))
print @nshiftmax
so it is retreiving the result 1/1/1900 11:59 p.m
and one more query is there
Declare @nshiftmax datetime
set @nshiftmax=convert(time,DATEADD(N,0,0))
print @nshiftmax
so it is retreiving the result 1/1/1900 12:00 a.m
how to same result in oracle query.
thanks in advance.952646 wrote:
Hi all,
Hope doing well,
sir i was using one query of sql that is here:
You mean you have these statements in SQL Server?
Please remember that SQL is an access language for relational databases. It is used by all of the major rdbms products. "SQL Server" is the name of Microsoft's rdbms product. Do not let Microsoft's marketing flaks lull you into thinking SQL = SQL Server.
Declare @nshiftmax datetime
set @nshiftmax=convert(time,DATEADD(N,1439,0))
print @nshiftmax
so it is retreiving the result 1/1/1900 11:59 p.m
and one more query is there
Declare @nshiftmax datetime
set @nshiftmax=convert(time,DATEADD(N,0,0))
print @nshiftmax
so it is retreiving the result 1/1/1900 12:00 a.m
how to same result in oracle query.
thanks in advance. -
Procedure output like a query in SQL developer?
Hi!
How can a PL procedure create output like a query in SQL developer?
This block
begin
for record in (
select * from my_db
loop
dbms_output.put_line(record.name ' ' || record.address)
end loop;
end;
would print a of names and adresses in my_db. However, output sent to a query result window which would be the result of
select name,address from my_db;
How could I make the PL block behave the same way as the SQL query, i.e. present its output in a query result window?Welcome to the forum!
Please provide your 4 digit Oracle version (result of SELECT * FROM V$VERSION) wheneve you ask a question.
Do you mean query a procedure as if it were a table?
You can do that with a pipelined function. Here is sample code you can test using the SCOTT schema
-- type to match emp record
create or replace type emp_scalar_type as object
(EMPNO NUMBER(4) ,
ENAME VARCHAR2(10),
JOB VARCHAR2(9),
MGR NUMBER(4),
HIREDATE DATE,
SAL NUMBER(7, 2),
COMM NUMBER(7, 2),
DEPTNO NUMBER(2)
-- table of emp records
create or replace type emp_table_type as table of emp_scalar_type
-- pipelined function
create or replace function get_emp( p_deptno in number )
return emp_table_type
PIPELINED
as
TYPE EmpCurTyp IS REF CURSOR RETURN emp%ROWTYPE;
emp_cv EmpCurTyp;
l_rec emp%rowtype;
begin
open emp_cv for select * from emp where deptno = p_deptno;
loop
fetch emp_cv into l_rec;
exit when (emp_cv%notfound);
pipe row( emp_scalar_type( l_rec.empno, LOWER(l_rec.ename),
l_rec.job, l_rec.mgr, l_rec.hiredate, l_rec.sal, l_rec.comm, l_rec.deptno ) );
end loop;
return;
end;
/Then you can query the function as if it were a table
select * from table(get_emp(20))Is that what you were looking for? -
My coldfusion service crashes intermitantly and when I check
the application logs the error that I see for the time frame is the
one below. Does anyone know where I might begain to solve this?
Thanks!
Error Executing Database
Query.coldfusion.sql.DatabaseConnectionException: Timed out trying
to establish connection The specific sequence of files included or
processed is: E:\wwwroot\lifeworks\default.cfmI'm no expert, but thought I would try to be helpful.
I was getting this same error on a regular basis.
The short term fix was to restart the ODBC server service.
The long term fix was twofold:
1. I recreated the ODBC connection in ColdFusion
Administrator to use the system connection (I was using the SA and
PW for login).
2. I created a second user ODBC connection as well as the
system one under ODBC in Windows Server 2003.
I haven't had the problem since.
I also read a pretty good set of "stuff" to try from the help
area:
http://www.adobe.com/cfusion/knowledgebase/index.cfm?id=tn_17277
Hope this helps.
Maybe you are looking for
-
ITunes no longer recognizes I have already purchased apps!
First, I use Unix. I am VERY unhappy that Apple forces me to either have a Windows or MAC installation to sync iPhone. After getting my iPhone the way I wanted it, I dumped Windows completely, not realizing that I was thus deleting my iTunes app and
-
Enhancing FI_GL_1
Hi friends I have a requiement to enhance the FI_GL_1 extractor. Now the extractor is bringing in only the local currencies. Now i neeed to populat the Group currencies as well . I looked into GLT0 table where these currencies are maitained and the e
-
Version 2 - Cannot open Connection window
Version 2.1.0.62 Build Main 62.61 Host - Windows XP. I have just installed this version, but cannot create a new connection. The connection window just does not appear. I have tried: - Clicking the Plus icon on the left panel. - Right clicking "Conne
-
All, I have been using ACR in Elements 9 since purchasing a D90 DSLR this winter. I recently noticed that in other ACR examples there are more than 3 tabs. After reading the FAQ it said that means I am actually using the Nikon plug-in, not Adobe's.
-
I was using hotmail yesterday using Firefox as my browser. As I was typing an email the print kept getting smaller and smaller. All folders and text in the inboxes is now so small I cannot read it. My only alternative is to use Internet Explorer as m