Read data ascii
salut
au cours de mon stage je suis demandé de faire une interface d'une balance CAS mwp 3000h , j'air ealisé une application labview a l'aide de l-interface visa et j'ai arrivé d'assurer d'acquisition des données mais le problème que la sortie en hexadécimal n'ai pas conforme la sortie fournie par le manual guide de la balance meme lorsque j'ai l'envoyé a un fichier txt jai trouvé des symboles . et merci
Attachments:
labview2014.vi 23 KB
Capture.PNG 94 KB
CAS_HA.pdf 288 KB
Thanks for the prompt reply! - I have changed the settings to the following:
Analog input task, continous, 16 samples, rate 100Hz, driver buffer 32
Analog output task, continous, 16 samples, rate 100Hz, driver buffer 32, output start after 32
In the "Data read" module the block size is now 16 at 100Hz
With this setting, DasyLab runs, but only for around 12 hours.
The following error occurs:
"Read date module name" / The data flow is blocked by one of the following modules.
Followed by:
Attempted to read samples that are no longer available. The requested sample was previously available, but has since been overwritten.
Is there something else I have to care? Could it be problematic to send signals from different modules to the same Chart Recorder module? I use DasyLab version 11.
Samuel
Similar Messages
-
Read Data (ASCII) and send to analog output
Hello
I have the following MAX configuration:
Analog input task, continous, 2 samples, rate 100Hz (PCI-6024E)
Analog output task, continous, 64 samples, rate 100Hz (PCI-6723)
The cards are synchronized by the RTSI bus.
With Dasylab I display signals from load cells by the input task. A "Read Data" module sends values to the output task. The "Read Data" module has the following settings: Output in realtime, synchronisation with analog input task, file is an ASCII, block size 4 values, no ascii time channel.
Additional settings for DAQmx are done by DasyLab:
Analog input: Driver buffer 30
Analog output: Driver buffer 30, output start after 2
When I start DasyLab I get a DAQmx failure (after a couple hours): DAQmxReadAnalogF64, Attempted to read samples that are no longer available. The requested sample was previously available, but has since been overwritten.
Could anyone please explain, how to configure analog input/output task and the DasyLab settings (Read Data)? - Attached the DasyLab diagram.
Additional information: The application should read and display signals from a test bench (load cells). The output shall feed external controllers. The input and output signals shall be displayed on the same chart (as realtime as possible).
Thank you
Regards Samuel
Attachments:
DasyLabDiagram.png 67 KBThanks for the prompt reply! - I have changed the settings to the following:
Analog input task, continous, 16 samples, rate 100Hz, driver buffer 32
Analog output task, continous, 16 samples, rate 100Hz, driver buffer 32, output start after 32
In the "Data read" module the block size is now 16 at 100Hz
With this setting, DasyLab runs, but only for around 12 hours.
The following error occurs:
"Read date module name" / The data flow is blocked by one of the following modules.
Followed by:
Attempted to read samples that are no longer available. The requested sample was previously available, but has since been overwritten.
Is there something else I have to care? Could it be problematic to send signals from different modules to the same Chart Recorder module? I use DasyLab version 11.
Samuel -
How to read an ascii file and record data in a 2d array
HI everyone,
I have an experimental data file in ascii format. It contains 10 data sets.
I'm trying to read the ascii file and record data in a 2d array for further analysis,
but I still could not figure it out how to do it.
Please help me to get this done.
Here I have attaced the ascii file.
-Sam
Attachments:
data.asc 123 KB
2015-01-27_18-01-31_fourier_A2-F-abs.zip 728 KBGot it!
Thank you very much !
-Pamsath -
Correct way to read/write ASCII data
Hi,
I am trying to read in ASCII data, manipulate it and write out as ASCII, but am getting values greater than 256 appearing. SHould I be using an encoding when I read/write and what is it.
Any advice appreciated.
MArkSmart quotes aren't part of the ASCII character set. If your character set includes them, it is possibly one of the so-called "extended ASCII" character sets that were created by various entities a few years ago. Java uses the Unicode character set, which includes ASCII as its first 128 characters. And the so-called smart quotes are mapped to the Unicode characters 201C ("LEFT DOUBLE QUOTATION MARK") and 201D. For more information about Unicode see http://www.unicode.org and for much more information on character sets in computing see for example http://www.czyborra.com.
-
Hi Everybody,
i'm playing a little bit with Windows Azure and I'm blocked with a really simple issue (or maybe not).
I've created a Cloud Service containing one simple Worker Role. I've configured an EndPoint in the WorkerRole configuration, which allows Input connections via tcp on port 10100.
Here the ServiceDefinition.csdef file content:
<?xml version="1.0" encoding="utf-8"?>
<ServiceDefinition name="EmacCloudService" xmlns="http://schemas.microsoft.com/ServiceHosting/2008/10/ServiceDefinition" schemaVersion="2014-01.2.3">
<WorkerRole name="TcpListenerWorkerRole" vmsize="Small">
<Imports>
<Import moduleName="Diagnostics" />
<Import moduleName="RemoteAccess" />
<Import moduleName="RemoteForwarder" />
</Imports>
<Endpoints>
<InputEndpoint name="Endpoint1" protocol="tcp" port="10100" />
</Endpoints>
</WorkerRole>
</ServiceDefinition>
This WorkerRole is just creating a TcpListener object listening to the configured port (using the RoleEnvironment instance) and waits for an incoming connection. It receives a message and returns a hardcoded message (see code snippet below).
namespace TcpListenerWorkerRole
using System;
using System.Net;
using Microsoft.WindowsAzure.ServiceRuntime;
using System.Net.Sockets;
using System.Text;
using Roche.Emac.Infrastructure;
using System.IO;
using System.Threading.Tasks;
using Microsoft.WindowsAzure.Diagnostics;
using System.Linq;
public class WorkerRole : RoleEntryPoint
public override void Run()
// This is a sample worker implementation. Replace with your logic.
LoggingProvider.Logger.Info("TcpListenerWorkerRole entry point called");
TcpListener listener = null;
try
listener = new TcpListener(RoleEnvironment.CurrentRoleInstance.InstanceEndpoints["Endpoint1"].IPEndpoint);
listener.ExclusiveAddressUse = false;
listener.Start();
LoggingProvider.Logger.Info(string.Format("TcpListener started at '{0}:{1}'", RoleEnvironment.CurrentRoleInstance.InstanceEndpoints["Endpoint1"].IPEndpoint.Address, RoleEnvironment.CurrentRoleInstance.InstanceEndpoints["Endpoint1"].IPEndpoint.Port));
catch (SocketException ex)
LoggingProvider.Logger.Exception("Unexpected exception while creating the TcpListener", ex);
return;
while (true)
Task.Run(async () =>
TcpClient client = await listener.AcceptTcpClientAsync();
LoggingProvider.Logger.Info(string.Format("Client connected. Address='{0}'", client.Client.RemoteEndPoint.ToString()));
NetworkStream networkStream = client.GetStream();
StreamReader reader = new StreamReader(networkStream);
StreamWriter writer = new StreamWriter(networkStream);
writer.AutoFlush = true;
string input = string.Empty;
while (true)
try
char[] receivedChars = new char[client.ReceiveBufferSize];
LoggingProvider.Logger.Info("Buffer size: " + client.ReceiveBufferSize);
int readedChars = reader.Read(receivedChars, 0, client.ReceiveBufferSize);
char[] validChars = new char[readedChars];
Array.ConstrainedCopy(receivedChars, 0, validChars, 0, readedChars);
input = new string(validChars);
LoggingProvider.Logger.Info("This is what the host sent to you: " + input+". Readed chars=" + readedChars);
try
string orderResultFormat = Encoding.ASCII.GetString(Encoding.ASCII.GetBytes("\xB")) + @"MSH|^~\&|Instrument|Laboratory|LIS|LIS Facility|20120427123212+0100||ORL^O34^ORL_O34| 11|P|2.5.1||||||UNICODE UTF-8|||LAB-28^IHE" + Environment.NewLine + "MSA|AA|10" + Environment.NewLine + @"PID|||patientId||""""||19700101|M" + Environment.NewLine + "SPM|1|sampleId&ROCHE||ORH^^HL70487|||||||P^^HL70369" + Environment.NewLine + "SAC|||sampleId" + Environment.NewLine + "ORC|OK|orderId|||SC||||20120427123212" + Encoding.ASCII.GetString(Encoding.ASCII.GetBytes("\x1c\x0d"));
writer.Write(orderResultFormat);
catch (Exception e)
LoggingProvider.Logger.Exception("Unexpected exception while writting the response", e);
client.Close();
break;
catch (Exception ex)
LoggingProvider.Logger.Exception("Unexpected exception while Reading the request", ex);
client.Close();
break;
}).Wait();
public override bool OnStart()
// Set the maximum number of concurrent connections
ServicePointManager.DefaultConnectionLimit = 12;
DiagnosticMonitor.Start("Microsoft.WindowsAzure.Plugins.Diagnostics.ConnectionString");
RoleEnvironment.Changing += RoleEnvironment_Changing;
return base.OnStart();
private void RoleEnvironment_Changing(object sender, RoleEnvironmentChangingEventArgs e)
// If a configuration setting is changing
LoggingProvider.Logger.Info("RoleEnvironment is changing....");
if (e.Changes.Any(change => change is RoleEnvironmentConfigurationSettingChange))
// Set e.Cancel to true to restart this role instance
e.Cancel = true;
As you can see, nothing special is being done. I've used the RoleEnvironment.CurrentRoleInstance.InstanceEndpoints to retrieve the current IPEndpoint.
Running the Cloud Service in the Windows Azure Compute Emulator everything works fine, but when I deploy it in Azure, then I receive the following Exception:
2014-08-06 14:55:23,816 [Role Start Thread] INFO EMAC Log - TcpListenerWorkerRole entry point called
2014-08-06 14:55:24,145 [Role Start Thread] INFO EMAC Log - TcpListener started at '100.74.10.55:10100'
2014-08-06 15:06:19,375 [9] INFO EMAC Log - Client connected. Address='196.3.50.254:51934'
2014-08-06 15:06:19,375 [9] INFO EMAC Log - Buffer size: 65536
2014-08-06 15:06:45,491 [9] FATAL EMAC Log - Unexpected exception while Reading the request
System.IO.IOException: Unable to read data from the transport connection: An existing connection was forcibly closed by the remote host. ---> System.Net.Sockets.SocketException: An existing connection was forcibly closed by the remote host
at System.Net.Sockets.NetworkStream.Read(Byte[] buffer, Int32 offset, Int32 size)
--- End of inner exception stack trace ---
at System.Net.Sockets.NetworkStream.Read(Byte[] buffer, Int32 offset, Int32 size)
at System.IO.StreamReader.ReadBuffer(Char[] userBuffer, Int32 userOffset, Int32 desiredChars, Boolean& readToUserBuffer)
at System.IO.StreamReader.Read(Char[] buffer, Int32 index, Int32 count)
at TcpListenerWorkerRole.WorkerRole.<>c__DisplayClass0.<<Run>b__2>d__0.MoveNext() in C:\Work\Own projects\EMAC\AzureCloudEmac\TcpListenerWorkerRole\WorkerRole.cs:line 60
I've already tried to configure an internal port in the ServiceDefinition.csdef file, but I get the same exception there.
As you can see, the client can connect to the service (the log shows the message: Client connected with the address) but when it tries to read the bytes from the stream, it throws the exception.
For me it seems like Azure is preventing the retrieval of the message. I've tried to disable the Firewall in the VM in Azure and the same continues happening.
I'm using Windows Azure SDK 2.3
Any help will be very very welcome!
Thanks in advance!
Javier
En caso de que la respuesta te sirva, porfavor, márcala como válida
Muchas gracias y suerte!
Javier Jiménez Roda
Blog: http://jimenezroda.wordpress.comhi Javier,
I changed your code like this:
private AutoResetEvent connectionWaitHandle = new AutoResetEvent(false);
public override void Run()
TcpListener listener = null;
try
listener = new TcpListener(
RoleEnvironment.CurrentRoleInstance.InstanceEndpoints["Endpoint"].IPEndpoint);
listener.ExclusiveAddressUse = false;
listener.Start();
catch (SocketException se)
return;
while (true)
IAsyncResult result = listener.BeginAcceptTcpClient(HandleAsyncConnection, listener);
connectionWaitHandle.WaitOne();
The HandleAsync method is your "While (true)" code:
private void HandleAsyncConnection(IAsyncResult result)
TcpListener listener = (TcpListener)result.AsyncState;
TcpClient client = listener.EndAcceptTcpClient(result);
connectionWaitHandle.Set();
NetworkStream netStream = client.GetStream();
StreamReader reader = new StreamReader(netStream);
StreamWriter writer = new StreamWriter(netStream);
writer.AutoFlush = true;
string input = string.Empty;
try
char[] receivedChars = new char[client.ReceiveBufferSize];
// LoggingProvider.Logger.Info("Buffer size: " + client.ReceiveBufferSize);
int readedChars = reader.Read(receivedChars, 0, client.ReceiveBufferSize);
char[] validChars = new char[readedChars];
Array.ConstrainedCopy(receivedChars, 0, validChars, 0, readedChars);
input = new string(validChars);
// LoggingProvider.Logger.Info("This is what the host sent to you: " + input + ". Readed chars=" + readedChars);
try
string orderResultFormat = Encoding.ASCII.GetString(Encoding.ASCII.GetBytes("\xB")) + @"MSH|^~\&|Instrument|Laboratory|LIS|LIS Facility|20120427123212+0100||ORL^O34^ORL_O34| 11|P|2.5.1||||||UNICODE UTF-8|||LAB-28^IHE" + Environment.NewLine + "MSA|AA|10" + Environment.NewLine + @"PID|||patientId||""""||19700101|M" + Environment.NewLine + "SPM|1|sampleId&ROCHE||ORH^^HL70487|||||||P^^HL70369" + Environment.NewLine + "SAC|||sampleId" + Environment.NewLine + "ORC|OK|orderId|||SC||||20120427123212" + Encoding.ASCII.GetString(Encoding.ASCII.GetBytes("\x1c\x0d"));
writer.Write(orderResultFormat);
catch (Exception e)
// LoggingProvider.Logger.Exception("Unexpected exception while writting the response", e);
client.Close();
catch (Exception ex)
//LoggingProvider.Logger.Exception("Unexpected exception while Reading the request", ex);
client.Close();
Please try it. For this error message, I suggest you could refer to this thread (http://stackoverflow.com/questions/6173763/using-windows-azure-to-use-as-a-tcp-server
) and this post (http://stackoverflow.com/a/5420788).
Regards,
Will
We are trying to better understand customer views on social support experience, so your participation in this interview project would be greatly appreciated if you have time. Thanks for helping make community forums a great place.
Click
HERE to participate the survey. -
Read an ascii file line by line
I am new with CVI, and I need to read an ascii file with multiple lines in the following format:
at_test_2_to_13=0.861000
at_testabcd_9_to_21=0.712000
at_abdgx_5_to_8=0.892000
here is the code for writing in the ascii file:
sprintf(ctResult, "%s=%f\n", TestName1,result1);
WriteFile (fileHdl,ctResult ,StringLength(ctResult) );
At a later time, I need to read the text file, find the test name (for example "at_testabcd_9_to_21") and record the value after the "=" sign (in this case 0.712000). The number of lines in the text file is not fixed.
I am writing the data to the file with no problems, but I am stack in reading the data.
I would appreciate any help on how to write this code in CVI.
Thank you in advance
Solved!
Go to Solution.As Wolfgang already proposed, you can use the ini-file library.
With this library, you can write the results in a structured manner and access an individual measurement by its name, without the need of reading every line above.
I also attached a sample project for what you asked.
Check the ini-file library help and samples for the other option.
S. Eren BALCI
www.aselsan.com.tr
Attachments:
AsciiRead.zip 2 KB -
LSMW in ECC6.0 - Read Data Error
Dear SAP Gurus,
I am trying to create an LSMW in ECC6.0 for uploading GL Masters data for Chart of Account. I have got thru till "Read Data"
On Executing "Read Data" I am getting this error
"Loading from front end is not allowed for packed/hexadec. fields"
This comes up even though I had not given "Hexadecimal Lth field" but nothing works and Code Page selected is ASCII (not IBM DOS)
Please Help!
ThanksSorry it doesnt works. I am not in a position to understand as to why this error is coming up at first place.
While specifying the file type I am giving the parameters correctly, that is, I am not giving the Code Page as IBM DOS.
Parameters:
File Contents: Data for One Source Structure
Delimiter: Tabulator
File Structure:
Field Names at Start of File
AND
File Type: Record End Marker (Text File)
Code Page: ASCII -
Hi guys..
I'm currently testing out on LSMW
I'm trying to create new material for transaction MM01.
But when i click on Step 9: Read Data
i get a shortdump
What happened?
The current ABAP program had to be terminated becaus
ABAP processor detected an internal system error.
The current ABAP program "/1CADMC/SAP_LSMW_READ_0000
because the ABAP
processor discovered an invalid system state.
1: SQL error
2: Invalid value in call
3: Screen number in header (field DNUM) and in ID
4: Internal error in the database interface
8: Memory filled (used up)
16: Buffer too small for data
32: Unkown table in call
64: Invalid selection
128: Object with this key exists more than once
Here is my source Fields
Source Fields
MM01SS MM01 Source Structure
MATNR C(018) Material
MBRSH C(001) Industry Sector
MTART C(004) Material Type
MEINS C(003) Base Unit Of Measure
MAKTX C(040) Material Description
Below are links to the field mapping stuff
<a href="http://img93.imageshack.us/img93/4043/1ju0.jpg">Screen shot 1</a>
<a href="http://img167.imageshack.us/img167/3240/2rn4.jpg">Screen shot 2</a>
the dummy.txt is having :
MATNR MBRSH MTART MEINS MAKTX
AC26 I aa BAG xxx1
AC27 I bb BAG xxx2
AC28 I aa BAG xxx3
AC29 I bb BAG xxx4
AC30 I aa BAG xxx5
AC31 I bb BAG xxx6
AC32 I aa BAG xxx7
AC33 I bb BAG xxx8
AC34 I aa BAG xxx9
AC35 I bb BAG xxx10
AC36 I aa BAG xxx11
AC37 I bb BAG xxx12
AC38 I aa BAG xxx13
AC39 I bb BAG xxx14
AC40 I aa BAG xxx15
AC41 I bb BAG xxx16
AC42 I aa BAG xxx17
AC43 I bb BAG xxx18
AC44 I aa BAG xxx19
AC45 I bb BAG xxx20
AC46 I aa BAG xxx21
AC47 I bb BAG xxx22
AC48 I aa BAG xxx23
Did i leave out anything?oh yea, one more thing , the file assigning part
Files
Legacy Data On the PC (Frontend)
Test data C:\Documents and Settings\XXXXXXX\Desktop\dummy.txt
Data for One Source Structure (Table)
Separator Tabulator
Field Names at Start of File
With Record End Indicator (Text File)
Code Page ASCII
Legacy Data On the R/3 server (application server)
Imported Data File for Imported Data (Application Server)
Imported Data TEST_CREATE_MATERIAL.lsmw.read
Converted Data File for Converted Data (Application Server)
Converted Data TEST_CREATE_MATERIAL.lsmw.conv
Wildcard Value Value for Wildcard '*' in File Name -
Trouble reading data from GPIB instrument using VISA
Hello, I am having trouble with reading data from a GPIB instrument in LabVIEW. It appears that the data that is returned from VISA read is incorrect. (I used NI Spy to verify what it should be and what I get, they are different) The odd thing is that when I use the VISA interactive control utility to get the data, it works perfectly. Is there some sort of VISA property that I need to set to get it to work right? Writing to the device seems to work correctly. If you need more info, please e-mail me @ [email protected] Thanks in advance!
What exactly do you mean when you say the data you are getting is incorrect? I'm guessing that you are dealing with some sort of data type issue. The VISA Read VI will return a set number of bytes in string (ASCII) format. If you are expecting a different data type, you will have to do some conversion by either using a type cast or string conversion function. The type cast function can be found in the Advanced-> Data Manipulation palette, while the string conversion functions can be found in the String palette.
-
View Object to read data from a java file
Hi,
I am using JDeveloper 11.1.1.4 and ADF-BC in my application.
For one of my view objects , I want the data to be read from a java file which exposes some method to return a collection.
I cannot use a static view object in this case.
Please suggest the best way to implement this requirement.Basically build a view object that should read data from a java file.
Thanks,
PraveenDepending on your use case you can either use a programmatic VO or directly expose the JV class as a data control.
http://docs.oracle.com/cd/E18941_01/tutorials/jdtut_11r2_36/jdtut_11r2_36.html -
Read data from SAP R/3 Class-System
Hello,
first of all sorry when I posted this into the wrong subforum, but I wasn't sure about that. My Question is how to read data from the Classystem I have specified in my ABAP report.
The goal is to read data from my individual class-system as well as data from MM and write them to a table that is to be read by another report. But right now I can't find information about the class system and abap. Maybe you know some tutorials or blogs about right that topic you can suggest?What class system have you specified in your report?
Normally a class can be used by declaring a variable of type of the class in question, if this class can be instantiated this is. If your class can't be instantiated, but it has only class methods, you can call this method directly.
But there is a lot more to this ABAP Object Oriented Programming, than just this short explanation. Search on SDN for some ABAP OO Tutorials.
some links:
http://help.sap.com/saphelp_nw2004s/helpdata/en/c3/225b5654f411d194a60000e8353423/frameset.htm
http://www.sapgenie.com/abap/OO/
https://www.sdn.sap.com/irj/sdn/go/portal/prtroot/docs/library/uuid/b6cae890-0201-0010-ef8b-f970a9c41d47
https://www.sdn.sap.com/irj/sdn/go/portal/prtroot/docs/library/uuid/1591ec90-0201-0010-3ba8-cdcd500b17cf
Transacation ABAPDOCU. -
Can not read data from URL!
Hello,
I want to read data from URL (http://84.100.130.82:8000/;stream.nsv). But can not do it. Because when try to call function openDataInputStream() shows this error: java.io.IOException: response does not start with HTTP it starts with: ICY. How I can fix this bug?
HttpConnection c = null;
InputStream is = null;
OutputStream os = null;
StringBuffer b = new StringBuffer();
String response,
responseLitle;
c = (HttpConnection)Connector.open(“http://84.100.130.82:8000/;stream.nsv”);
os = c.openOutputStream();
os.flush();
is = c.openDataInputStream(); // ERROR CODE HERE
int ch;
// receive output
while ((ch = is.read()) != -1)
b.append((char) ch);
response = b.toString();Regards, RamunasHi, I�m trying to do the same as above, get MP3 from a Shoutcast server.
I got the same fault ("response does not start with HTTP it starts with: ICY") when I tried to open an HttpConnection as bellow:
============================================
HttpConnection conn = (HttpConnection) Connector.open("http://64.236.34.196/stream/1074");
Then I tried to open a socket connection as bellow:
======================================
SocketConnection conn = (SocketConnection) Connector.open("socket://64.236.34.196:80");
String get = "GET /stream/1074 HTTP/1.1";
DataOutputStream os = conn.openDataOutputStream();
os.writeUTF(get);
InputStream is = conn.openInputStream();
But then I got the following error:
=========================
java.lang.SecurityException: Target port denied to untrusted applications
Could someone help me to find out what is going on?
Thanks a lot! -
Read data from excel sheet and then perform the required operations.
Hi all
I need to write a procedure which can read data from excel sheet.I have excel sheet in which i have to options one is modification and other is addition.so if it reads modification then i need to read the concerned table name then check its availability in pl-sql datbase.If table exists then reading the realated column in that row to fire the querry. The excel sheet is saved in local disk c.
can anybody help me with this.How i need to start specialy to read the data from excel sheet saved in local disk c.
Edited by: user13334062 on Jun 30, 2010 3:45 AMHi
If you can convert the excel to a csv format, then it can be simply query from DB Creating Oracle External Tables. Best part is that you may still change the CSV using EXCEL.
Following action Points can be adopt;
*1. Convert Excel File to a csv. File Save as CSV*
*2. Create Oracle Directory* ( This has to be the location of your excel file )
SQL> Create directory mydir as 'C:\testdb'; --- "testdb" is the location folder in win for your excel sheet.
*3. Create the External Table*
SQL> create table my_ext_tab (
Field1 Datatype,
Field2 Datatype,
Field3 Datatype,
Field4 Datatype,
Field5 Datatype
Organization external
(type oracle_loader default directory mydir
access parameters (records delimited by newline fields terminated by ',')
location ('my_ext_tab.csv'))
reject limit 100;
*4. Now you can query the table "my_ext_tab"*
Select * from "my_ext_tab";
Please avoid the reformat the data column inside the spreadsheet (CSV). -
Error reading data from CLOB column into VARCHAR2 variable
Hi all,
Am hitting an issue retrieving data > 8K (minus 1) stored in a CLOB column into a VARCHAR2 variable in PL/SQL...
The "problem to be solved" here is storing DDL, in this case a "CREATE VIEW" statement, that is longer than 8K for later retrieval (and execution) using dynamic SQL. Given that the EXECUTE IMMEDIATE statement can take a VARCHAR2 variable (up to 32K(-1)), this should suffice for our needs, however, it seems that somewhere in the process of converting this VARCHAR2 text to a CLOB for storage, and then retrieving the CLOB and attempting to put it back into a VARCHAR2 variable, it is throwing a standard ORA-06502 exception ("PL/SQL: numeric or value error"). Consider the following code:
set serveroutput on
drop table test1;
create table test1(col1 CLOB);
declare
cursor c1 is select col1 from test1;
myvar VARCHAR2(32000);
begin
myvar := '';
for i in 1..8192 loop
myvar := myvar || 'a';
end loop;
INSERT INTO test1 (col1) VALUES (myvar);
for arec in c1 loop
begin
myvar := arec.col1;
dbms_output.put_line('Read data of length ' || length(myvar));
exception when others then
dbms_output.put_line('Error reading data: ' || sqlerrm);
end;
end loop;
end;
If you change the loop upper bound to 8191, all works fine. I'm guessing this might have something to do with the database character set -- we've recently converted our databases over to UTF-8, for Internationalizion support, and that seems to have changed underlying assumptions regarding character processing...?
As far as the dynamic SQL issue goes, we can probably use the DBMS_SQL interface instead, with it's EXECUTE procedure that takes a PL/SQL array of varchar2(32K) - the only issue there is reading the data from the CLOB column, and then breaking that data into an array but that doesn't seem insurmountable. But this same basic issue (when a 9K text block, let's say, turns into a >32K block after being CLOBberred) seems to comes up in other text-processing situations also, so any ideas for how to resolve would be much appreciated.
Thanks for any tips/hints/ideas...
JimFor those curious about this, here's the word from Oracle support (courtesy of Metalinks):
RESEARCH
========
Test the issue for different DB version and different characterset.
--Testing the following PL/SQL blocks by using direct assignment method(myvar := arec.col1;) on
different database version and different characterset.
SQL>create table test1(col1 CLOB);
--Inserting four CLOB data into test1.
declare
myvar VARCHAR2(32767);
begin
myvar := RPAD('a',4000);
INSERT INTO test1 (col1) VALUES (myvar);
myvar := RPAD('a',8191);
INSERT INTO test1 (col1) VALUES (myvar);
myvar := RPAD('b',8192);
INSERT INTO test1 (col1) VALUES (myvar);
myvar := RPAD('c',32767);
INSERT INTO test1 (col1) VALUES (myvar);
commit;
end;
--Testing the direct assignment method.
declare
cursor c1 is select col1, length(col1) len1 from test1;
myvar VARCHAR2(32767);
begin
for arec in c1 loop
myvar := arec.col1;
--DBMS_LOB.READ(arec.col1, arec.len1, 1, myvar);
dbms_output.put_line('Read data of length: ' || length(myvar));
end loop;
end;
The following are the summary of the test results:
===================================
1. If the database characterset is WE8ISO8859P1, then the above direct assignment
method(myvar := arec.col1;) works for database version 9i/10g/11g without any
errors.
2. If the database characterset is UTF8 or AL32UTF8, then the above direct assignment method(myvar := arec.col1;) will generate the "ORA-06502:
PL/SQL: numeric or value error" when the length of the CLOB data is greater
than 8191(=8K-1). The same error can be reproduced across all database versions
9i/10g/11g.
3. Using DBMS_LOB.READ(arec.col1, arec.len1, 1, myvar) method to read CLOB data into a VARCHAR2 variable works for both WE8ISO8859P1 and UTF8
characterset and for all database versions.
So - it seems as I'd surmised, UTF8 changes the way VARCHAR2 and CLOB data is handled. Not too surprising, I suppose - may you all be lucky enough to be able to stay away from this sort of issue. But - the DBMS_LOB.READ workaround is certainly sufficient for the text processing situations we find ourselves in currently.
Cheers,
Jim C. -
Without loops how can i read data from associative Array??
Hi all,
I am facing scenario like...
i need to read data from associative array without using loops is it possible,
CREATE OR REPLACE PACKAGE BODY test_pkg IS
TYPE t1 IS TABLE OF NUMBER INDEX BY BINARY_INTEGER;
-- in array we can expect more than one row or sometimes no data also.
FUNCTION test1(vt1 T1 DEFAULT CAST(NULL AS t1)) RETURN NUMBER IS
BEGIN
-- basically in array we'll get data of column2
-- this loop should satisfies table1.colum2 = nvl(NULL, table2.colum2 )if array is null.
-- if array is not null then only compare with array values
FOR i IN (SELECT t1.colum1,t1.column2
FROM table1 t1, table1 t2
WHERE t1.colum1 = t2.column1
AND t1.colum2 = nvl(vt1, t2.colum2)
LOOP
generateTEXT(i.colum1, i.colum2);
END LOOP;
END test1;
END test_pkg;
in table1 we have date like...
colum1 column2
Jan 1
Feb 2
Mar 3
if i call select test_pkg.test1(1) from dual then output should
be Jan..
and
select test_pkg.test1(null) from dual then it should display all elements from table1.
Jan 1
Feb 2
Mar 3,
Thanks for your quick replay..i need to read data from associative array without using loops is it possible,
No - you would need to create a SQL type and then use the TABLE operator to unnest the collection.
create or replace TYPE my_nums IS TABLE OF INTEGER;
DECLARE
-- TYPE my_nums IS TABLE OF PLS_INTEGER INDEX BY PLS_INTEGER;
v_nums my_nums := my_nums(1, 2, 3);
v_total number;
BEGIN
select sum(column_value) into v_total from table(v_nums);
DBMS_OUTPUT.PUT_LINE
('Sum of the numbers is ' || TO_CHAR(v_total));
END;
Sum of the numbers is 6
Maybe you are looking for
-
[SOLVED] X won't start after update
I'm running Arch inside a virtual machine, with Virtualbox. I ran 'sudo pacman -Syu' and let it install everything. It updated a bunch of xorg-* packages, among a few other things, and then I rebooted. Now it seems like X has stopped working. Normall
-
Blackmagic Intensity Pro Video Card
I am in need of a HDTV/HDMI video out solution when playing back Quicktime movies in Logic Pro 8. Can anyone report success with the Blackmagic Intensity Pro card? Or are there better alternatives (besides Firewire out). Thanks.
-
Photoshop hotkeys are intermittently pulling down menus instead of switching tools
I am currently using Photoshop CS5. When I try to use hotkeys to switch tools, instead of switching them, menus from the menu bar will drop. For example, I hit "E" for the eraser tool, but instead of switching to the eraser the Edit menu drops. I hav
-
IPod Touch gen. 2 not booting up.
I have had the strangest errors with my iPod the last month. First the iPod goes crazy and recieves touches all over the display without me or anyone else touching it. So I'm having a loot of problems trying to turn it off because the iPod keeps laun
-
Funds not appearing in bank account
Hi there everyone, I'm aware that this question may have been asked a thousand times but will ask again anyway! I transferred money from my PayPal account to my bank account a number of days ago and the funds have yet to show up in my bank account. D