How to get PL/SQL output in Excelsheet & preserve trailing zero for VARCHAR
Hi All,
I am trying to get the PL/SQL procedure out put to Excel sheet, I have wrote below code and it worked fine.
CREATE OR REPLACE PROCEDURE plsql_to_excel_demo IS
CURSOR cur_stock_details
IS
SELECT *
FROM stocks;
outfile UTL_FILE.file_type;
l_chr_string VARCHAR2(100);
l_chr_col_header VARCHAR2(100);
l_chr_file VARCHAR2(100);
l_chr_date VARCHAR2(20);
BEGIN
SELECT TO_CHAR(sysdate,'DD_MON_YYYY')
INTO l_chr_date
FROM dual;
l_chr_col_header :='SYMBOL'||CHR(9)||'COMPANY'||CHR(9)||'CURRENT_PRICE'||CHR(9)||'TRADE_DATE'||CHR(9)||'NUMBER_TRADED_TODAY'
||CHR(9)||'TODAYS_HIGH'||CHR(9)||'TODAYS_LOW';
l_chr_file := 'STOCK_REPORTS_'||l_chr_date||'.xls';
outfile := UTL_FILE.FOPEN ('/u01/app/UTL/out',l_chr_file, 'W');
UTL_FILE.PUT_LINE(outfile,l_chr_col_header);
FOR rec_stock_details IN cur_stock_details LOOP
/*l_chr_string := rec_stock_details.symbol||CHR(9)||''''||rec_stock_details.company||''''||CHR(9)
||rec_stock_details.current_price||CHR(9)||
TO_CHAR(rec_stock_details.trade_date,'DD/MM/YYYY')||CHR(9)||rec_stock_details.number_traded_today||CHR(9)||
rec_stock_details.todays_high||CHR(9)||rec_stock_details.todays_low;
l_chr_string := rec_stock_details.symbol||CHR(9)||rec_stock_details.company||CHR(9)||rec_stock_details.current_price||CHR(9)||
TO_CHAR(rec_stock_details.trade_date,'DD/MM/YYYY')||CHR(9)||rec_stock_details.number_traded_today||CHR(9)||
rec_stock_details.todays_high||CHR(9)||rec_stock_details.todays_low;
UTL_FILE.PUT_LINE(outfile,l_chr_string);
END LOOP;
UTL_FILE.FCLOSE (outfile);
EXCEPTION
WHEN OTHERS THEN
dbms_output.put_line ('Error in main '||SQLERRM);
END plsql_to_excel_demo;
I am facing the issue when I have VARCHAR2 column say Company in stocks table with value as 0000234. When I get the data Excel
sheet I can only see 234
for company name. I want to preserve the trailing zeros while getting the output in Excel sheet.
I have tried with adding single quote (') please see the commented part in the above code, but it will give me output in company
column in excel '0000234' which i don't want.
Is there any way I can make this work and only get 0000234 as company name in Excel.
Thanks for reading the post..
regards,
Shyam.
Edited by: Suryawanshi on Mar 22, 2010 5:40 PM
Yes, that should be a client (excel, or open office in my case) issue.
I stole some code from http://asktom.oracle.com/pls/asktom/f?p=100:11:0::::P11_QUESTION_ID:95212348059 to test this out.
Adding a single quote to the beginning of the string worked fine with my version of Open Office, should work for your Excel as well.
create table varchar2_test(col1 varchar2(10), col2 number(10));
insert into varchar2_test values ('000189', 10);
create or replace function dump_csv( p_query in varchar2,
p_separator in varchar2 default ',',
p_dir in varchar2 ,
p_filename in varchar2 )
return number
is
l_output utl_file.file_type;
l_theCursor integer default dbms_sql.open_cursor;
l_columnValue varchar2(2000);
l_status integer;
l_colCnt number default 0;
l_separator varchar2(10) default '';
l_cnt number default 0;
begin
l_output := utl_file.fopen( p_dir, p_filename, 'w' );
dbms_sql.parse( l_theCursor, p_query, dbms_sql.native );
for i in 1 .. 255 loop
begin
dbms_sql.define_column( l_theCursor, i, l_columnValue, 2000 );
l_colCnt := i;
exception
when others then
if ( sqlcode = -1007 ) then exit;
else
raise;
end if;
end;
end loop;
dbms_sql.define_column( l_theCursor, 1, l_columnValue, 2000 );
l_status := dbms_sql.execute(l_theCursor);
loop
exit when ( dbms_sql.fetch_rows(l_theCursor) <= 0 );
l_separator := '';
for i in 1 .. l_colCnt loop
dbms_sql.column_value( l_theCursor, i, l_columnValue );
utl_file.put( l_output, l_separator || l_columnValue );
l_separator := p_separator;
end loop;
utl_file.new_line( l_output );
l_cnt := l_cnt+1;
end loop;
dbms_sql.close_cursor(l_theCursor);
utl_file.fclose( l_output );
return l_cnt;
end dump_csv;
variable x number;
begin
:x := dump_csv
p_query => 'select '''' || col1, col2 from varchar2_test',
p_separator => ',',
p_dir => 'TEST_DIR',
p_filename => 'test_output.xls'
end;
print :x
Similar Messages
-
Hi All,
How to get the physical SQL query for the OBIEE reports.
Thanks in advance,
Haree.Hi Anitha,
Thanks for your reply,
I am getting XML script in log file. (Settings > Administration > Manage Sessions > View Log).
How to get physical SQL query ?
Thanks,
Haree -
How to get the Query output to Excel
Hi ,
Can you tell me how to get the Query output to excel with out using any third party tool?
Can you tell me how to write the code in Webservice and call it..
Please explain it Elaboartly..
Thanks in Advance!!!
Miniwhats your source system?
you can use Live office, or query as a webservice if you are getting data from universe
if you're getting data from SAP BI query and you have a java stack on your netweaver then you can get the data directly using sap bi connector in xcelsius.
good luck -
How to get the SQL Signon that Agent Jobs "Run As" or "Executed as User"
How to get the SQL Signon that Agent Jobs "Run As" or "Executed as User"?
I have an install SQL scripts that creates a Linked Server. I want to put some security on the Linked Server and only grant the Agent Job Signon (the "Run As" or "Executed as User") access to the linked server. I need to retrieve the
Agent Job Signon (something like "NT SERVICE\SQLAgent$FIDEV360BI02").
I could query certain jobs and SUBSTRING the Message column - using some form of the query below, which would return "Executed as user: NT SERVICE\SQLAgent$SSDEVBI02. The step succeeded." But that is pretty imprecise.
use msdb
SELECT [JobName] = JOB.name,
[Step] = HIST.step_id,
[StepName] = HIST.step_name,
[Message] = HIST.message,
[Status] = CASE WHEN HIST.run_status = 0 THEN 'Failed'
WHEN HIST.run_status = 1 THEN 'Succeeded'
WHEN HIST.run_status = 2 THEN 'Retry'
WHEN HIST.run_status = 3 THEN 'Canceled'
END,
[RunDate] = HIST.run_date,
[RunTime] = HIST.run_time,
[Duration] = HIST.run_duration,
[Retries] = HIST.retries_attempted
FROM sysjobs JOB
INNER JOIN sysjobhistory HIST ON HIST.job_id = JOB.job_id
-- CHANGE THIS
-- WHERE JOB.name like '%GroupMaster%' or Job.name like '%etlv%'
ORDER BY HIST.run_date, HIST.run_timeby default all sql jobs are executed as sql server agent account, unless otherwise a proxy is setup.
you can get the proxy information as Olaf mentioned, if the proxy_id is null for the step, it implies that the job step was executed as sql server service account and in such case it will be null
so, if it is null, it ran as sql server agent account.
so, one work around is get the sql server agent service account and if the proxy is null, that means it ran as sql server agent account, so, use isnull function. the disadvantage would be if the sql server agent account was switched, you might not get the
accurate information as the new account will show up though the job really ran as old account, to get this information, you need to get this from the logmessage column as you mentioned above.
try this code...
/*from sql 2008r2 sp1, you get the service accounts using tsql,otherwise you have to query the registry keys*/
declare @sqlserveragentaccount varchar(2000)
select @sqlserveragentaccount= service_account
from sys.dm_server_services
where servicename like '%sql%server%agent%'
select message,isnull(name,@sqlserveragentaccount) as AccountName
from sysjobhistory a inner join sysjobsteps b
on a.step_id=b.step_id and a.job_id=b.job_id
left outer join sysproxies c on c.proxy_id=b.proxy_id
Hope it Helps!! -
How to get automatic message output
Hi,
How to get automatic message output while creating po cause i have done all setting in the config but still it does not work what else i have to do.
And 1 more thing how we can maintain condition record for Printoutput & External send for one output type.
Regards,
AnantHi,
Please follow the below steops for the Output of Purchase Order
1. Condition Table
SPRO > Material Management> Purchasing -> Message -> Output Control->Condition Tables->Define Condition Table for Purchase Order
Select:
Purchasing Doc. Type, Purch. Organization, Vendor
2. Access Sequences
SPRO -> -> Purchasing -> Message -> Output Control->Access Sequences->Define Condition Table for Purchase Order
3. Message Type
SPRO -> Material Management-> Purchasing -> Message -> Output Control->Message Types->Define Message Type for Purchase Order
*4. Message Determination Schemas*
4.1. Message Determination Schemas
SPRO -> Material Management-> Purchasing -> Message -> Output Control->Message Schema->Define Message Schema for Purchase Order-> Maintain Message Determination Schema
4.2. Assign Schema to Purchase Order
SPRO -> Material Management-> Purchasing -> Message -> Output Control->Message Schema->Define Message Schema for Purchase Order-> Assign Schema to Purchase Order
5. Partner Roles per Message Type
SPRO -> Material Management-> Purchasing -> Message -> Output Control-> Partner Roles per Message Type ->Define Partner Role for Purchase Order
6. Condition Record
Navigation Path: SAP Menu-> Logistics -> Material Management -> Purchasing-> Master data-Messages- MN04
Here you can maintain the condition record.
All above steps u can do from transacton NACE also
now when u create po in the messages u will get the out put method as u have maintained in the above steps.
Regards,
Manish -
How to get the object class field value in CDHDR table for vendor
hi
how to get the object class field value in CDHDR table for vendorTry KRED/KRED_N as object class in CDHDR for Vendor.
-
I am trying to figure out how to get the pre made "beats" with my garage band for my MacBook Air can u help
Hello Mattxy2,
Thank you for the question. It sounds like you would like to add some Apple Loops to your project. I recommend reviewing the following sections in Garageband Help:
GarageBand Help - Search for Apple Loops
http://help.apple.com/garageband/mac/10.0/#gbnd3002ab64
GarageBand Help - Add Apple Loops to your projects
http://help.apple.com/garageband/mac/10.0/#gbndc1d3db81
Thank you for using Apple Support Communities.
Best,
Sheila M. -
How to get the pricing hierarchy based on the delivery date for sales order
Hi,
How to get the pricing hierarchy based on the delivery date for sales order other than system date.
My requirement is to get the Pricing hierarchy based on the delivery date other than system date.
Waiting for kind response.
Best Regards,
BDPHI Sai,
please refer teh document already how to write FM based extration on generic extractors.
and here the logic to find the latest records values:-
-> get the data in an internal table
->Sort the internal table data based from date descending
-> Using READ statement , we can read the first record of the table which is nothign but your latest record.
Regards.
Sakthi -
I bought two films on my ipod tough 4g ( normally comes up on my ipad if i have bought something on my ipod) but i dont know how to get the two films on my ipad without paying for them.
Movies work differant than TV shows, music and apps. With movies, to get them from one device such as an iPod Touch to an iPad, you would need to connect the Touch to your computer first and in iTunes under the file menu, hit transfer purchases. Next connect the iPad and you can sync the movie to the iPad.
While the iPad is connected to the computer, in iTunes, click on the iPad in the left pane and when the screen loads, click movies and from there, you can select the movie that you want to sync. -
How to get the desired output in the format ...?
Hi all,
I am having data like this.
Col1 col2 col3
1 2 1
1 2 2
1 2 3
2 3 7
2 3 8
2 3 9
I want to output the data like this
1 2 1,2,3
2 3 7,8,9
How to get this.
Thanks in advance,
PalIn simple sql...
Connected to:
Oracle Database 10g Enterprise Edition Release 10.2.0.1.0 - Production
With the Partitioning, OLAP and Data Mining options
SQL> select * from t
2 /
COL1 COL2 COL3
1 2 1
1 2 2
1 2 3
2 3 7
2 3 8
2 3 9
6 rows selected.
SQL> select max(decode(rno,1,to_number(col1||col2||col3))) col1, max(decode(rno,2,col3)) col2, max(decode(rno,3,col3)) col3
2 from (select row_number() over(partition by col1,col2 order by col3) rno, t.*
3 from t)
4 group by col1
5 /
COL1 COL2 COL3
121 2 3
237 8 9
SQL>Thanks,
Karthick. -
How to get the SQL queries based on SQL_ID.
Hi Experts,
I want to get the SQL queries based on SQL_ID.
I have tried the following query,but I am not getting full query.
[code]SET linesize 132 pagesize 999
column sql_fulltext format a60 word_wrap
break on sql_text skip 1
SELECT REPLACE (TRANSLATE (sql_text, '0123456789', '999999999'), '9', ''),sql_id
FROM dba_hist_sqltext s
WHERE s.sql_id = '7tvurftg8zryb';[/code]
One of my friend said use grid to get full query text.
Can you please help me how to use grid ,else any other method to get the full query based on SQL_ID.
Please help me.
Thanks in advance.You have these many options to set, if sql_text is really huge. But better use a tool(TOAD) as it's really helpful and easy to use instead! (See my previous comment).
column sql_text format A10000
set echo off
set head off
set feed off
set verify off
set termout off
set lines 10000
set long 1000000
set trimspool on
set pages 0
Thanks! -
I cannot figure how to get the text(SQL statement) from a system view(i guess it is in a system view... but witch??). 'Till now i have the sql_address and the sql_hash_value..
I know it is possible.. EM does it ... so i should be able to do the same..
ps:I use 9.2v$sql ?
-
How to get multiple html output file from an xml document via xslt?
Hi,
the purpose is to generate multiple html output file from one xml file
depending on special tag.
exp: i have an xml file which contains sevreral articles so how to get each article section in an independant html file
Thanks for helpNot a standard feature of XSLT. But Michael Kay's XSLT implementation, SAXON, provides that as an extension. Get it here:
http://saxon.sourceforge.net/ -
How to get XML format output from Hyperion Financial Reporting
Dears,
We are using Hyperion Financial Reporting to replace FSG in fusion. I found that Hyperion FR report can be exported to html/excel/pdf format. However, I would like the report to export to xml format.It means I only need the xml data source.
Anyone who knows how to get the xml format output from Hyperion FR, is there any avaiable API?I think if you export the report, you will be able to open the .des file in Notepad/Wordpad and see xml content.
-
How to get the sql which executing?
I want to know the query sql runing in timesten? how can I get it?
For example, in oracle 9i we can use below sql to get the query sql runinig in oracle.
1.select OSUSER, PROGRAM, USERNAME, SCHEMANAME, B.Cpu_Time, STATUS, B.SQL_TEXT
2. from V$SESSION A
3. LEFT JOIN V$SQL B ON A.SQL_ADDRESS = B.ADDRESS
4. AND A.SQL_HASH_VALUE = B.HASH_VALUE
5. order by b.cpu_time desc
thanks!Sorry, there is no way to get this information in TimesTen. You can use internal tracing to see each SQL statement as it is executed but (a) the performance hit is severe and (b) there is no timing or CPU usage information available.
If you want to know how long a specific SQL statement takes to execute you need to add timing instrumentation to your application code.
Chris
Maybe you are looking for
-
How to create a Master delivery plan
Hello, my question is how to create a Master delivery plan to my customers manuelly and how to setup up it for to be able to create automatically the production planning orders. Thank you kindly for you answers.
-
Derby and case (in)sensitivity
Hello, from my present understanding it looks to me that all queries in Derby are case sensitive. Is there a way (I did not discover yet) to make case insensitive queries such as SELECT * FROM table WHERE name="washington" although the actual db-entr
-
PO transfer to backend with Qty = 0
Hi, We have SRM3.0 backend ECC6.0 Scenario is classic extended. We have a 2 items PO changed in SRM with Qty and Price to 0 (2 items marked with del_ind = X. Control is ok in SRM, but as soon as document is transferred to backend when saving the PO k
-
Hi all, How do I pass multiple itab values into the Event container --> WF container ? I have created a multiline container element with import parameter and expression: Append Table...but it is not working... Any ideas anyone? cheers john
-
WRT54GL: Random spikes/DCs with Vent and WoW
About a year ago I've changed from a wired to a wireless connection due to me moving to another apartment. During the time on the wired setup I never experienced any problems but now I have a problem. A couple of months ago I've started playing WoW a