Insert query using fn-bea:execute-sql() function
Hi ,
How to use sql insert query in Xquery function fn-bea:execute-sql().
Could you please anyone help me on this.
Regards
Rajesh.
Hi
Can i use stored procedure in that function to include insert query?
could you please suggest me on this.
Please provide some links or tutorial on that.
Regards
Rajesh
Similar Messages
-
How to get multiple records using fn-bea:execute-sql()
Hi,
I created Proxy service(ALSB3.0) to get records from DB table. I have used Xquery function(fn-bea:execute-sql()). Using simple SQL query I got single record, but my table having multiple records. Please suggest how to get multiple records using fn-bea:execute-sql() and how to assign them in ALSB variable.
Regards,
Nagaraju
Edited by: user10373980 on Sep 29, 2008 6:11 AMHi,
Am facing the same issue stated above that I couldnt get all the records in the table that am querying in the Proxyservice.
For example:
fn-bea:execute-sql('EsbDataSource', 'student', 'select Name from StudentList' ) is the query that am using to fetch the records from the table called StudentList which contains more than one records like
Id Name
01 XXX
02 YYY
03 ZZZ
I tried to assign the result of the above query in a variable and while trying to log the variable, I can see the below
<student>
<Name>XXX</Name>
</student>
I want to have all the records from my table in xml format but it's not coming up. I get the value only from the first row of my table.
Please suggest.
regards,
Venkat -
Unable to use fn-bea:execute-sql() in an XQuery in Workspace Studio 1.1
When we create an XQuery file in Workspace Studio 1.1 (ALSB 3.0), we are unable to use fn-bea:execute-sql(). It throws an error saying "unknown function". It doesnt allow us to publish the XQuery file to ALSB instance due to the "unknown function" error. However if we directly upload this file to ALSB console, it accepts it and the execute-sql function also works grrat. Can you please let us know if we have to configure anything on the Workspace studio to be able to use XQuery Extensions for Service Bus ? Or can you please let us know if we should declare any namespace in the XQuery file to use fn-bea:execute-sql() in Workspace studio ?
It sounds like a bug. Can you please contact bea support?
Gregory Haardt
ALSB Prg. Manager
[email protected] -
OSB10.3.1 fn-bea:execute-sql - nullable columns and type conversion
Hi all,
we are using the fn-bea:execute-sql function to retrieve data from an Oracle db:
<ctx:route><ctx:service>{
fn-bea:execute-sql (
fn:concat(xs:string($body/urn:clientDataLookup/ds/text()),'.SADataSource'),
'resultset',
'SELECT id, name, type_id, domi_country_id, open_date, close_date FROM my_table WHERE id=?',
xs:string($body/urn:clientDataLookup/id/text())
</ctx:service></ctx:route>
Where my_table is defined as below:
CREATE TABLE my_table
ID NUMBER,
NAME VARCHAR2(100 BYTE),
TYPE_ID NUMBER,
DOMI_COUNTRY_ID NUMBER,
OPEN_DATE DATE,
CLOSE_DATE DATE,
As you can see ID,TYPE_ID,DOMI_COUNTRY_ID are defined as NUMBER and some columns could be null.
Below an example of the result from the above query using fn-bea:execute-sql function:
<resultset>
<ID>161052.0</ID>
<NAME>...</NAME>
<TYPE_ID>3.0</TYPE_ID>
<DOMI_COUNTRY_ID>2090.0</DOMI_COUNTRY_ID>
<OPEN_DATE>2010-12-17T00:00:00</OPEN_DATE>
</resultset>
In the above example the column CLOSE_DATE is null for the given ID and the CLOSE_DATE tag, as you can see, is not included in the result.
In addition the values for the columns defined as NUMBER are returned with decimals.
Is there any way to return also tags for columns that are NULL ? E.g. something like <CLOSE_DATE null="Y"/> ?
And for the columns defined as NUMBER that are returned with decimals what could we do to force the type without decimals ?
We are wondering if fn-bea:execute-sql function accepts any extra param in order 'to drive' result format/structure ... as expected ...
Thanks in advance
ferpIt sounds like a bug. Can you please contact bea support?
Gregory Haardt
ALSB Prg. Manager
[email protected] -
I have a script task written in C# that creates an array of strings "arrayFields" after parsing a text file. It saves the array of strings in a DTS variable.
Each row in array represents a row is comma separated and is a row that must be inserted into a table. For example,
X and Z are fields in the table
X1, X2,....Xn
Z1,Z2,...Zn
I am using a Foreach Loop to grab each row and then Execute SQL Task to take each row from the array and insert each field per row in a table,
The SQL is something like,
INSERT dbo.table values(field1, field2,...fieldn) arrayFields?
What should this this INSERT look like?I guess you implemented
Shredding a Recordset
Based on what I understood (correct me if I am wrong) you have difficulties mapping the input parameters, if so here is the guide
http://www.sqlis.com/sqlis/post/The-Execute-SQL-Task.aspx
In short it might look like
INSERT dbo.table (ColumnA, ColumnB,...) VALUES (?,?...)
The syntax for the T-SQL INSERT is http://technet.microsoft.com/en-us/library/dd776381%28v=sql.105%29.aspx
Arthur
MyBlog
Twitter -
How to build dynamic query strings in the query using DB adapter 'Pure SQL'
Dear Forum,
I am building an application which will access DB to fetch some result set. The query involves retrieving data from multiple tables(nearly 10 tables). So I have created a DB adapter using 'execute pure sql' option. With this query works fine, but my inputs parameters will vary. So I need to make my query dynamic to append the query strings at runtime depending on the inputs.
For example I have 3 input variables - input1,input2 and input3 (in my request xsd) which are used in the pure sql query. Now if I get a 4th input parameter input4 in the request, I need to append this to query string as 'AND input4=[some value]' at runtime. Otherwise my query should have only 3 parameters. Please suggest how this can be achieved.
Regards,
Satya.This is a strange requirement, depending on the columns you have and what are optional in them, one way is to have separate operations and each opeartion will have different inputs and for each operation , a different DB Adapter is called. But this way, it results in more number of operations for the service as well as more number of references in the composite. Even if you pass the column inputs to the SQL procedure, it will result in a large number of if-else cases..
Thanks,
N -
Using Union in Execute SQL Task
I am using the following SQL statement in an Excute SQL Task:
declare @RespAreaSubAreaID int, @UserLevelID int, @SubmittedByUserID int, @RespAreaID int, @SubAreaID int
Set @RespAreaSubAreaID = ?
Set @SubmittedByUserID = ?
Set @UserLevelID = ?
set @RespAreaID = ?
set @SubAreaID = ?
select users.User_EmailAddress + ';' As CC
from users inner join UserLevelsNotificationFrequencys on users.user_Id = UserLevelsNotificationFrequencys.User_id
where UserLevelID = @UserLevelID and RespAreaSubAreaID = @RespAreaSubAreaID and (NotificationFrequencyID = 4 and users.user_id <> @SubmittedByUserID)
union
select users.User_EmailAddress + ',' As CC
from users inner join UserLevelsNotificationFrequencys on users.user_Id = UserLevelsNotificationFrequencys.User_id
where UserLevelID = @UserLevelID and RespAreaSubAreaID = @RespAreaSubAreaID and (NotificationFrequencyID = 1)
I have my parameter mapped correctly. My results set is set to xml because I want it all in one string to use as a variable named User:CC. On the Result Set tab the result name is 0 and the variable name is User:CC. When I run my package I am getting
the error below. Can I not do a union query in the execute SQL task? I tried to not declare anything and just map to each of the variables that I am passing in the order that they are needed but that didn't work either. Thanks in advance for your help in this
matter.
[Execute SQL Task] Error: Executing the query "declare @RespAreaSubAreaID int, @NotificationID
in..." failed with the following error: "Syntax error, permission violation, or other nonspecific error". Possible failure reasons: Problems with the query, "ResultSet" property not set correctly, parameters not set correctly, or connection
not established correctly.
Reach for the unknown!Thank you for your reply but I am not using the Data Flow. All my work is happening on the Control Flow. I am looping through a set of records and emailing them to the correct
people. Setting my result set to XML worked for the To Line (See my earlier post Execute SQL task for Email ToLine using COALESCE and two variables) and now I am working on the CC line which is more complicated because it uses a union statement.
Reach for the unknown! -
SSIS - Using Variables in Execute SQL Task Error
The following query in my Execute SQL Task throws the following error when run - [Execute SQL Task] Error: Executing the query "SELECT @columnz = COALESCE(@columnz + ',[' + times..." failed with the following error:
"Must declare the scalar variable "@columnz".". Possible failure reasons: Problems with the query,
"ResultSet" property not set correctly, parameters not set correctly, or connection not established correctly.
Query:
drop table tmpNCPCNCDownstreamMaxUtilization3wks
select node, max(utilization) as max_Utilization, DATE
into tmpNCPCNCDownstreamMaxUtilization3wks
from stage_ncpcncdownstream_temporal
WHERE Date BETWEEN DATEADD(day, -20, GETDATE()) AND GETDATE()
group by node, date
order by node
go
alter table tmpNCPCNCDownstreamMaxUtilization3wks add Timestamp varchar(50)
go
update tmpNCPCNCDownstreamMaxUtilization3wks
set Timestamp = 'WeekOf_' + cast(left(Date, 11) as varchar)
go
--drop table tmpNCPCNC_DownstreamNodeUtilizationMaxPivot
--go
declare @columnz varchar (8000)
go
SELECT @columnz = COALESCE(@columnz + ',[' + timestamp + ']','[' + timestamp+ ']')
FROM tmpNCPCNCDownstreamMaxUtilization3wks group by timestamp order by timestamp
go
--pivot contents in @columns
declare @query varchar(8000)
SET @query ='select * into tmpNCPCNC_DownstreamNodeUtilizationMaxPivot from
(select node, timestamp, Max_Utilization from tmpNCPCNCDownstreamMaxUtilization3wks)a
pivot
sum(max_Utilization) for timestamp in('+ @columnz +')
)as p'
execute (@query)
--empty contents from NCPCNCDownstreamMaxUtilization3wks
update tmpNCPCNCDownstreamMaxUtilization3wks
set timestamp =''
truncate table tmpNCPCNC_MaxDownstreamNodeUtilzationChart3Week
--load to table to be joined to Node feature class
insert into tmpNCPCNC_MaxDownstreamNodeUtilzationChart3Week
(Node, TwoWeeksAgo, PreviousWeek, CurrentWeek)
select * from tmpNCPCNC_DownstreamNodeUtilizationMaxPivot
--calculate average utilization for all values in each record
update tmpNCPCNC_MaxDownstreamNodeUtilzationChart3Week
set average = (coalesce(twoweeksago, 0) + coalesce(previousweek, 0) + coalesce(currentweek, 0))/3
from tmpNCPCNC_MaxDownstreamNodeUtilzationChart3Week
ScottIssue is with variable @columnz.
Scope of variables is only limited to the batch and if batch is over Variable is no more accessible.
Reproduce Steps:
DECLARE @columnz int = 0
Go --Scope of @columnz ends here
SELECT @columnz -- Ends up with error
So you have to remove GO keyword. I have commented 2 of them in below:
DROP TABLE tmpNCPCNCDownstreamMaxUtilization3wks
SELECT node
,max(utilization) AS max_Utilization
,DATE
INTO tmpNCPCNCDownstreamMaxUtilization3wks
FROM stage_ncpcncdownstream_temporal
WHERE DATE BETWEEN DATEADD(day, - 20, GETDATE())
AND GETDATE()
GROUP BY node
,DATE
ORDER BY node
GO
ALTER TABLE tmpNCPCNCDownstreamMaxUtilization3wks ADD TIMESTAMP VARCHAR(50)
GO
UPDATE tmpNCPCNCDownstreamMaxUtilization3wks
SET TIMESTAMP = 'WeekOf_' + cast(left(DATE, 11) AS VARCHAR)
GO
--drop table tmpNCPCNC_DownstreamNodeUtilizationMaxPivot
--go
DECLARE @columnz VARCHAR(8000)
--GO
SELECT @columnz = COALESCE(@columnz + ',[' + TIMESTAMP + ']', '[' + TIMESTAMP + ']')
FROM tmpNCPCNCDownstreamMaxUtilization3wks
GROUP BY TIMESTAMP
ORDER BY TIMESTAMP
--GO
--pivot contents in @columns
DECLARE @query VARCHAR(8000)
SET @query = 'select * into tmpNCPCNC_DownstreamNodeUtilizationMaxPivot from
(select node, timestamp, Max_Utilization from tmpNCPCNCDownstreamMaxUtilization3wks)a
pivot
sum(max_Utilization) for timestamp in(' + @columnz + ')
)as p'
EXECUTE (@query)
--empty contents from NCPCNCDownstreamMaxUtilization3wks
UPDATE tmpNCPCNCDownstreamMaxUtilization3wks
SET TIMESTAMP = ''
TRUNCATE TABLE tmpNCPCNC_MaxDownstreamNodeUtilzationChart3Week
--load to table to be joined to Node feature class
INSERT INTO tmpNCPCNC_MaxDownstreamNodeUtilzationChart3Week (
Node
,TwoWeeksAgo
,PreviousWeek
,CurrentWeek
SELECT *
FROM tmpNCPCNC_DownstreamNodeUtilizationMaxPivot
--calculate average utilization for all values in each record
UPDATE tmpNCPCNC_MaxDownstreamNodeUtilzationChart3Week
SET average = (coalesce(twoweeksago, 0) + coalesce(previousweek, 0) + coalesce(currentweek, 0)) / 3
FROM tmpNCPCNC_MaxDownstreamNodeUtilzationChart3Week
-Vaibhav Chaudhari -
Using sp_MSforeachtable in a SQL function.
I am trying to build a SQL function to return the KB size of all tables in a database. I am trying to use
sp_MSforeachtable inside the function. "Unresolved reference to [sys].[sp_MSforeachtable]." How do I
fix this?
INSERT INTO #TableSpaceUsed
EXEC sys.sp_MSforeachtable 'sp_spaceused ''?''';sp_MSforeachtable is an undocumented command. Use it for fun and entertainment but not for production.
The following blog is on the same topic:
http://www.sqlusa.com/bestpractices2008/table-sizes/
In addition you can build a dynamic SQL cursor loop to carry out your task. Just follow the example in the following blog:
http://www.sqlusa.com/bestpractices2008/rebuild-all-indexes/
You can get the source code sp_spaceused:
exec sp_helptext 'sp_spaceused';
Kalman Toth Database & OLAP Architect
sqlusa.com
Paperback / Kindle: Pass SQL Exam 70-461 & Job Interview: Programming SQL Server 2012 -
Using variables in PL/SQL function body returning SQL query
h4. okay so I have this procedure POSTCODE_TO_LAT_LNG_GM_API(postcode IN VARCHAR2, lat OUT NUMBER, p_long OUT NUMBER) to convert a postcode into lat/long values. I then need to add them to the returned SQL statement so I used the string concat operator || with to_char but it comes up with this error when I try to apply the changes: Query cannot be parsed within the Builder. If you believe your query is syntactically correct, check the ''generic column'' checkbox below the region source to proceed without parsing.
ORA-00936: missing expressionh4. Does anyone know what I am doing wrong here I have tried so many different ways round and none seem to work!! :/
h4. btw I'm using Oracle 11g release 11.2.0.3.0 and Apex version 4.1.1.00.23
DECLARE
l_lat NUMBER;
l_lng NUMBER;
l_SDO_GEOMETRY SDO_GEOMETRY;
l_query VARCHAR2(30000);
BEGIN
POSTCODE_TO_LAT_LNG_GM_API (:P1_POSTCODE, l_lat, l_lng);
l_query := 'select
CAR_ID, CAR_NAME, CAR_POSTCODE,
SDO_GEOM.SDO_DISTANCE(car_location, SDO_GEOMETRY(2001,
8307,
SDO_POINT_TYPE(' || to_char(l_lng) || ','
|| to_char(l_lat) || ',
NULL),
NULL,
NULL),
0.005, ''UNIT=MILE'') DISTANCE
from CARS';
RETURN l_query;
END;Okay so did a little playing around and eventually got it to work, the SQL Command didn't help with the function FYI (maybe something to do with it testing SQL statements and not PL/SQL?).
My 1st problem was that one of my columns relied on an apex text box which isn't always filled in so the SQL Compiler didn't like that. To solve this I did an IF NOT NULL, ELSE statement.
My 2nd problem was after I did that i didn't have a value for Distance in the ELSE statement and so APEX didn't know weather or not to add a Distance column. I solved this by making the distance column NULL.
Here is my final working code:
DECLARE
l_lat NUMBER;
l_lng NUMBER;
l_SDO_GEOMETRY SDO_GEOMETRY;
l_query VARCHAR2(30000);
BEGIN
IF :P1_POSTCODE IS NOT NULL THEN
POSTCODE_TO_LAT_LNG_GM_API (:P1_POSTCODE, l_lat, l_lng);
l_query := 'select
CAR_ID, CAR_NAME, CAR_DESC, CAR_MAKE, CAR_MODEL, CAR_MILEAGE, CAR_PRICE, CAR_YEAR, CAR_POSTCODE,
SDO_GEOM.SDO_DISTANCE(car_location, SDO_GEOMETRY(2001,
8307,
SDO_POINT_TYPE(' || l_lng || ','
|| l_lat || ',
NULL),
NULL,
NULL),
0.005, ''UNIT=MILE'') DISTANCE,
dbms_lob.getlength(CAR_IMAGE_SMALL) CAR_IMAGE_SMALL,
CAR_FUEL_TYPE, CAR_TRANSMISSION, CAR_ENGINE_SIZE, CAR_NUM_DOORS, CAR_BODY_TYPE, CAR_COLOUR
from CARS';
ELSE
l_query := 'select
CAR_ID, CAR_NAME, CAR_DESC,
NULL Distance,
dbms_lob.getlength(CAR_IMAGE_SMALL) CAR_IMAGE_SMALL,
CAR_FUEL_TYPE, CAR_TRANSMISSION, CAR_ENGINE_SIZE, CAR_NUM_DOORS, CAR_BODY_TYPE, CAR_COLOUR
from CARS';
END IF;
RETURN l_query;
END;So yer problem solved now, thanks to you guys for trying to help out!! =) -
SQL query using Group by and Aggregate function
Hi All,
I need your help in writing an SQL query to achieve the following.
Scenario:
I have table with 3 Columns. There are 3 possible values for col3 - Success, Failure & Error.
Now I need a query which can give me the summary counts for distinct values of col3 for each GROUP BY of col1 and col2 values. When there are no values for col3 then it should return ZERO count.
Example Data:
Col1 Col2 Col3
abc 01 success
abc 02 success
abc 01 success
abc 01 Failure
abc 01 Error
abc 02 Failure
abc 03 Error
xyz 07 Failure
Required Output:
c1 c2 s_cnt F_cnt E_cnt (Heading)
abc 01 2 1 1
abc 02 1 1 0
abc 03 0 0 1
xyz 07 0 1 0
s_cnt = Success count; F_cnt = Failure count; E_cnt = Error count
Please note that the output should have 5 columns with col1, col2, group by (col1,col2)count(success), group by (col1,col2)count(failure), group by (col1,col2)count(error)
and where ever there are NO ROWS then it should return ZERO.
Thanks in advance.
Regards,
ShivaHi,
user13015050 wrote:
Thanks TTT. Unfortunately I cannot use this solution because I have huge data for this.T's solution is basically the same as mine. The first 23 lines just simulates your table. Since you actually have a table, you would start with T's line 24:
SELECT col1 c1, col2 c2, SUM(decode(col3, 'success', 1, 0)) s_cnt, ...
user13015050 wrote:Thanks a lot Frank. It helped me out. I just did some changes to this as below and have no issues.
SELECT col1
, col2
, COUNT ( CASE
WHEN col3 = 'SUCCESS'
THEN 1
END
) AS s_cnt
, COUNT ( CASE
WHEN col3 = 'FAILED'
THEN 1
END
) AS f_cnt
, COUNT ( CASE
WHEN col3 = 'ERROR'
THEN 1
END
) AS e_cnt
FROM t1
WHERE c2 in ('PURCHASE','REFUND')
and c4 between to_date('20091031000000','YYYYMMDDHH24MISS') AND to_date('20100131235959','YYYYMMDDHH24MISS')
GROUP BY c1, c2
ORDER BY c1, c2;
Please let me know if you see any issues in this query.It's very hard to read.
This site normally compresses spaces. Whenever you post formatted text (such as queries or results) on this site, type these 6 characters:
\(small letters only, inside curly brackets) before and after each section of formatted text, to preserve spacing.
Also, post exactly what you're using. The code above is SELECTing col1 and col2, but there's no mention of either in the GROUP BY clause, so I don't believe it's really what you're using.
Other than that, I don't see anything wrong or suspicious in the query. -
How to execute our own Insert Query using EJB3.0 and Toplink
Hi,
This is my scenario. I want to insert master record and then detail record.
Initially i followed this way
UnitOfWork uow = getSessionFactory().acquireUnitOfWork();
final EgovAgencyDetails egovAgency =
(EgovAgencyDetails)uow.executeQuery("findAgencyRegistrationNo",
EgovAgencyDetails.class, eGovPOMasterBean.getAgencyRegistrationNo());
EgvoPaymentorderMaster po = (EgvoPaymentorderMaster)uow.newInstance
(EgvoPaymentorderMaster.class);
po.setSupplierName(-----);
uow.commit();
Then i inserted detail record. the same find the master record and then inserted detail record in the table.
But if detail record fails means i want to rollback the master record.
For that i followed below steps in my custom method in session facade,
SQLCall sqlCall = new SQLCall("INSERT INTO EMPLOYEE (L_NAME) VALUES (#last_name)");
UpdateObjectQuery query = new UpdateObjectQuery(myEmployee);
query.setCall(sqlCall);
query.addArgument("last_name"); // input
query.bindAllParameters();
Vector arguments = new Vector();
arguments.add("MacDonald");
uow.executeQuery(query, arguments);
final EgvoPaymentorderMaster poMaster =
(EgvoPaymentorderMaster)uow.executeQuery("findEgovPOID", EgvoPaymentorderMaster.class, eGovPOMasterBean.getPoNumber());
EgovPaymentorderDetail poDetailInstance = (EgovPaymentorderDetail)uow.newInstance
(EgovPaymentorderDetail.class);
poMaster .addEgovPaymentorderDetail(poDetailInstance);
Since if detail record failed means i want to rollback.
I am getting this exception. Pleas kindly provide what changes i need to do.
[TopLink Warning]: 2008.03.15 01:05:48.931--UnitOfWork(12731542)--Exception [TOPLINK-6014] (Oracle TopLink - 10g Release 3 (10.1.3.3.0) (Build 070608)): oracle.toplink.exceptions.QueryException
Exception Description: Objects cannot be written during a UnitOfWork, they must be registered.
Query: WriteObjectQuery(mof.egov.model.EgvoPaymentorderMaster@126df42)
08/03/15 13:05:48 --- Inside Catch Method --- :
Exception Description: Objects cannot be written during a UnitOfWork, they must be registered.
Query: WriteObjectQuery(mof.egov.model.EgvoPaymentorderMaster@126df42)
Local Exception Stack:
Exception [TOPLINK-6014] (Oracle TopLink - 10g Release 3 (10.1.3.3.0) (Build 070608)): oracle.toplink.exceptions.QueryException
Exception Description: Objects cannot be written during a UnitOfWork, they must be registered.
Query: WriteObjectQuery(mof.egov.model.EgvoPaymentorderMaster@126df42)
at oracle.toplink.exceptions.QueryException.invalidQuery(QueryException.java:536)
at oracle.toplink.queryframework.ObjectLevelModifyQuery.executeInUnitOfWorkObjectLevelModifyQuery(ObjectLevelModifyQuery.java:86)
at oracle.toplink.queryframework.ObjectLevelModifyQuery.executeInUnitOfWork(ObjectLevelModifyQuery.java:72)
at oracle.toplink.publicinterface.UnitOfWork.internalExecuteQuery(UnitOfWork.java:2604)
at oracle.toplink.publicinterface.Session.executeQuery(Session.java:993)
at oracle.toplink.publicinterface.Session.executeQuery(Session.java:965)
at mof.egov.model.MasterDetailSessionEJBBean.insertPaymentOrder(MasterDetailSessionEJBBean.java:391)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:585)
Thanks & Regards
Vimalan BalanC,
I don't use TopLink, but I suggest you set the "processEscapes" [Oracle database connection] property to "true", as described in the JDBC User's Guide and Reference.
Oracle documentation can be accessed from here:
http://www.oracle.com/technology/documentation/index.html
Good Luck,
Avi. -
Pl/sql function body returning SQL query - Print function
Hello all,
I have pl/sql function body returning SQL query for my reports for my new project that I am developing. We dont have any BI tool or anything for APEX so we use Oracle reports to get the same reports to be printed in PDF format. I had been using SQL function for Reports all these days and grabbing the data using SQL query was easy in Oracle reports. But this time we had atleast 8 fields in search criteria and hence I thouhgt PL/sql function body returning SQL query could be something easy to handle that scenario. We have 11 such reports in our project. Now when we tried to use the same PL/sql function to oracle reports , I was told by one of our Oracle reports expert, that we have to write it into functions and use it in SQL query to get the Reports in Oracle reports. Is there any Easy way to convert the same Pl/SQL function or get a PDF format of the same report in APEX without going thru the much pains of rewriting the whole SQL Query.
thank you
DevisriHi,
give this a go.
I can't test it as I don't have the tables in my schema.
create or replace package MK_TEST_PF is
-- Author : MK
-- Created : 21/06/2010 16:30:19
-- Purpose : FOR LUCY_DISCOVER
-- Public type declarations
/* -- just guess the table row types.....
-- otherwise it won't compile
type test_rec is record
(INV REP.inv%type
,cNUMBER REP.cNUMBER%type
,OPENDATE REP.OPENDATE%type
,TARGETDATE REP.ESTCOMPLETE%type
,DATECLOSED REP.COMPLETED%type
,STATUS REP.STATUS%type
,cCODE REP.cCODE%type
,line varchar2(4000)
,SIGc varchar2(4000)
,CLASS REP.CLASS%type
,SUMM REP.SUMM%type
,AREA REP.AREA%type
type test_rec is record
(INV varchar2(4000)
,cNUMBER varchar2(4000)
,OPENDATE varchar2(4000)
,TARGETDATE varchar2(4000)
,DATECLOSED varchar2(4000)
,STATUS varchar2(4000)
,cCODE varchar2(4000)
,line varchar2(4000)
,SIGc varchar2(4000)
,CLASS varchar2(4000)
,SUMM varchar2(4000)
,AREA varchar2(4000)
type test_tab is table of test_rec;
-- Public constant declarations
-- Public variable declarations
-- Public function and procedure declarations
end MK_TEST_PF;
create or replace package body MK_TEST_PF is
-- Private type declarations
-- Private constant declarations
-- Private variable declarations
-- Function and procedure implementations
function get_query_f
(p_inv VARCHAR2 := UPPER(v('P44_INV'))
,p_reg VARCHAR2 := UPPER(v('P44_CLASS'))
,p_proarea VARCHAR2 := UPPER(v('P44_PROGRAM_AREA'))
,p_disp VARCHAR2 := UPPER(v('P44_DISPOSITION'))
,p_coding VARCHAR2 := UPPER(v('P44_CODING'))
,p_status VARCHAR2 := UPPER(v('P44_STATUS'))
,p_SIG VARCHAR2 := UPPER(v('P44_SIG_c'))
,p_inc_sum VARCHAR2 := UPPER(v('P44_INCLUDE_SUMM_FIELD'))
,p_word VARCHAR2 := UPPER(v('P44_WORD_IN_SUMM'))
,p_timeframe VARCHAR2 := UPPER(v('P44_TIME_FRAME'))
,p_rec VARCHAR2 := UPPER(v('P44_RECORD_KEEPING'))
,p_WORD_IN_SUMM VARCHAR2 := UPPER(v('P44_WORD_IN_SUMM'))
,p_ON_AFTER VARCHAR2 := UPPER(v('P44_ON_AFTER'))
,p_ON_BEFORE VARCHAR2 := UPPER(v('P44_ON_BEFORE'))
return varchar2
is
v_sql VARCHAR2(5000);
-- v_inv VARCHAR2(100);
-- v_reg VARCHAR2(100);
-- v_proarea VARCHAR2(100);
-- v_status VARCHAR2(100);
-- v_SIG VARCHAR2(100);
-- v_disp VARCHAR2(100);
-- v_coding VARCHAR2(100);
-- v_inc_sum VARCHAR2(4);
-- v_word VARCHAR2(4000);
v_wildcard VARCHAR2(2000);
-- v_timeframe VARCHAR2(100);
-- v_rec VARCHAR2(5);
v_record VARCHAR2(5);
v_open VARCHAR2(100);
v_closed VARCHAR2(100);
v_PEND VARCHAR2(100);
v_refSIG VARCHAR2(100);
v_refreg VARCHAR2(100);
v_refother VARCHAR2(100);
v_y varchar2(100);
BEGIN
--v_inv := UPPER(v('P44_INV')) ;
v_record := 'R%';
v_wildcard := '%';
v_open := 'OPEN';
v_closed := 'CLOSED';
v_PEND := 'PEND';
v_refSIG := 'REF - SIG';
v_refreg := 'REF - CLASS';
v_refother := 'REF - OTHER';
v_y := 'Y';
v_sql := 'SELECT REP.INV as INV, REP.cNUMBER as cNUMBER, REP.OPENDATE as OPENDATE,
REP.ESTCOMPLETE as TARGETDATE, REP.COMPLETED as DATECLOSED, REP.STATUS as STATUS,
REP.cCODE as cCODE, apex_item.checkbox(1,REP.line,null,'''||v_y||''') line , apex_item.checkbox(1,REP.SIG,null,'''||v_y||''') SIGc ,
REP.CLASS as CLASS, REP.SUMM as SUMM, REP.AREA as AREA from REP where 1=1';
IF p_rec is not null then
IF p_rec = 'E' then
v_sql := v_sql|| ' and upper(REP.cnumber) not like '''||v_record||'''';
ELSIF p_rec = 'D' then
v_sql := v_sql|| ' and upper(REP.cnumber) like '''||v_record||'''';
ELSIF p_rec = 'I' then
v_sql := v_sql|| ' and REP.cnumber = REP.cnumber ';
end if ;
end if ;
IF upper(p_status) not like '%NULL%' then
IF upper(p_status) like '%OPEN%' then
v_sql := v_sql||' AND upper(REP.status) like '''||v_open||'''';
ELSIF upper(p_status) like '%CLOSED%' then
v_sql := v_sql||' AND upper(REP.status) like '''||v_closed||'''';
ELSIF upper(v_PEND) like '%PEND%' then
v_sql := v_sql||' AND upper(REP.status) like '''||v_PEND||'''';
ELSIF upper(v_refSIG) like '%REF - SIG%' then
v_sql := v_sql||' AND upper(REP.status) like '''||v_refSIG||'''';
ELSIF upper(v_refreg) like '%REF - CLASS%' then
v_sql := v_sql||' AND upper(REP.status) like '''||v_refreg||'''';
ELSIF upper(v_refother) like '%REF - OTHER%' then
v_sql := v_sql||' AND upper(REP.status) like '''||v_refother||'''';
END IF ;
END IF ;
IF p_inv = 'NULL' THEN
v_sql := v_sql||' AND instr(upper(REP.INV),'''||p_inv||''') > 0';
END IF ;
IF p_reg = 'NULL' THEN
v_sql := v_sql||' AND instr(upper(REP.CLASS),'''||p_reg||''') > 0';
END IF ;
IF p_proarea = 'NULL' THEN
v_sql := v_sql||' AND instr(upper(REP.AREA),'''||p_proarea||''') > 0';
END IF ;
IF p_disp = 'NULL' THEN
v_sql := v_sql||' AND instr(upper(REP.disposition),'''||p_disp||''') > 0';
END IF ;
IF p_coding = 'NULL' THEN
v_sql := v_sql||' AND instr(upper(REP.ccode),'''||p_coding||''') > 0';
END IF ;
IF p_SIG = ' ' THEN
v_sql := v_sql||' AND instr(upper(REP.SIG),'''||p_SIG||''') > 0';
END IF ;
IF p_word is not null then
v_sql := v_sql|| ' and
instr(upper(REP.SUMM),
upper(nvl('''||p_WORD_IN_SUMM||''',REP.SUMM))) > 0';
end if ;
If p_timeframe is not null then
if upper(p_timeframe) = 'OPEN' then
v_sql := v_sql|| ' and to_date(REP.opendate) between to_date ('''||p_ON_AFTER||''') and to_date('''||p_ON_BEFORE||''')';
elsif upper(p_timeframe) = 'CLOSED' then
v_sql := v_sql|| ' and to_date(REP.completed) between to_date ('''||p_ON_AFTER||''') and to_date('''||p_ON_BEFORE||''')';
elsif upper(p_timeframe) = 'EST' then
v_sql := v_sql|| ' and to_date(REP.estcomplete) between to_date ('''||p_ON_AFTER||''') and to_date('''||p_ON_BEFORE||''')';
end if;
end if;
v_sql := v_sql ||' order by REP.INV ';
return v_sql;
end get_query_f;
function test_pf
(p_inv VARCHAR2 := UPPER(v('P44_INV'))
,p_reg VARCHAR2 := UPPER(v('P44_CLASS'))
,p_proarea VARCHAR2 := UPPER(v('P44_PROGRAM_AREA'))
,p_disp VARCHAR2 := UPPER(v('P44_DISPOSITION'))
,p_coding VARCHAR2 := UPPER(v('P44_CODING'))
,p_status VARCHAR2 := UPPER(v('P44_STATUS'))
,p_SIG VARCHAR2 := UPPER(v('P44_SIG_c'))
,p_inc_sum VARCHAR2 := UPPER(v('P44_INCLUDE_SUMM_FIELD'))
,p_word VARCHAR2 := UPPER(v('P44_WORD_IN_SUMM'))
,p_timeframe VARCHAR2 := UPPER(v('P44_TIME_FRAME'))
,p_rec VARCHAR2 := UPPER(v('P44_RECORD_KEEPING'))
,p_WORD_IN_SUMM VARCHAR2 := UPPER(v('P44_WORD_IN_SUMM'))
,p_ON_AFTER VARCHAR2 := UPPER(v('P44_ON_AFTER'))
,p_ON_BEFORE VARCHAR2 := UPPER(v('P44_ON_BEFORE'))
RETURN test_tab PIPELINED
is
type test_c is ref cursor;
v_row test_tab;
v_sql varchar2(4000);
v_cursor test_c;
begin
v_sql := get_query_f
(p_inv
,p_reg
,p_proarea
,p_disp
,p_coding
,p_status
,p_SIG
,p_inc_sum
,p_word
,p_timeframe
,p_rec
,p_WORD_IN_SUMM
,p_ON_AFTER
,p_ON_BEFORE
open v_cursor for v_sql;
fetch v_cursor bulk collect into v_row;
close v_cursor;
for i in 1 .. v_row.count loop
pipe row (v_row(i));
end loop;
return;
end test_pf;
end MK_TEST_PF;
/Regards
Michael -
Environment: SQL Server 2008 R2
Code:
CREATE TABLE dbo.PkgAudit
PkgAuditID INT IDENTITY(1, 1),
PackageName VARCHAR(100),
LoadTime DATETIME ,
NumberofRecords VARCHAR(50),
Status1 VARCHAR(50),
Status2 VARCHAR(50),
The following code is inserted in the SQL Task Execute Editor
INSERT INTO dbo.PkgAudit(PackageName
,LoadTime
,NumberofRecords
,Status1
,Status2
) VALUES(?,?,?,?,?)
Screen Shot (Parameter Mapping):
Problem: an error Message occurred when I hit Parse Query Button in the Execute SQL Task Editor, "Execute SQL: Task Editor: The query failed to parse. Syntax error, permission violation, or other nonspecific error". How I could Solve this
problemDifferent connection providers require different Parameter syntax. E.g. ADO @ParameterName notatoin, not just an offset of 0,1 etc.
Arthur My Blog -
Error Using LISTAGG SQL Function
Hello,
I'm trying to use the new LISTAGG SQL function with the following expression in a report:
select listagg(email, ';') within group (order by email) as email_list from sba_registration_entries where team=241
and I get the following SQL error in Apex SQL Workshop:
ORA-00923: FROM keyword not found where expected
Is this function enabled on the apex.oracle.com site? Am I using the correct syntax?Hi,
The current database on apex.oracle.com is "Oracle Database 11g Enterprise Edition Release 11.1.0.6.0 - Production"
The LISTAGG function seems to be from version 11.2: [http://download.oracle.com/docs/cd/E11882_01/server.112/e10592/functions087.htm] ?
Andy
Maybe you are looking for
-
Is there a way to change the message received in Outlook from Mavericks calender?
Hi there I found a post discussing this whereby a user was advised to edit the ITIP.stings file in the contents of the iCal.app to change the standard message that states "To accept or decline this invitation, click the link below" etc message that a
-
Multiple computers, one ipod?
New ipod, probably old problem, appreciate help. Using ipod with two computers, each set to manual organization of music in itunes. Wish to get both computers on "same page" and then auto-sync b/c it is apparently a large annoyance to manual sync. Ca
-
Subject changes when Reply email
Hi, I have a Z1 (C6943) with KitKat 4.4.4 (14.4.A.0.157) and I'm experiencing an issue when replying to any mail. My ROM is in spanish, and the mail client always prepends the word "RESPODER: " ("REPLY: ") to the subject, even when the subject alread
-
i want to programatically save the pdf file open on the screen. iam using dotnet. is there any library to do this ??@
-
Web.xml: security-constraint [un]usable in JSF?
<security-constraint> in web.xml is a simple, effective and portable method of declaring a web application�s security policies. It's been noted, however, in an earlier topic (http://forum.java.sun.com/thread.jspa?threadID=747919&messageID=4279347) th