Truncate field before insert
Suppose I have the following:
table: mytable
field: username (VARCHAR2(35))
field: zip (VARCHAR2(5))
I am importing data from an excel file with columns username and zip. A couple of the usernames contain more than 35 characters, and some of the zipcodes are in the xxxxx-xxxx format, thus containing more than 5 characters.
I attempted to write a before insert trigger to truncate the data before they are inserted. For any username that is above 35 characters from the excel file, just truncate the username to the first 35 characters. Similarly, for any zip code that is above 5 characters, just truncate the zip to the first 5 characters.
The trigger for the zip codes:
CREATE OR REPLACE
TRIGGER trigger_zipc
BEFORE INSERT
ON mytable
FOR EACH ROW
BEGIN
SELECT substr(:new.zip, 1, 5)
INTO :new.zip
from dual;
END;
However, I get the error: ORA-12899: value too large for column
I've read on other forums that this is what happens, and that a possible work around is to use INSERT INSTEAD??
Can anyone give me a solution or point me in the right direction?
Can anyone give me a solution or point me in the right direction?
Sure - the 'right direction' is to mark this thread ANSWERED and repost your question in the Sql and Pl/Sql forum:
PL/SQL
This forum is ONLY for Sql Developer questions and your question doesn't appear to have anything to do with that tool.
As the exception says the value is too large for the column. Your code that tries to trim the value will NEVER be executed because the exception occurs BEFORE it ever gets that far.
The buffer that Oracle creates to hold that :NEW value is too small to hold the value you try to insert - that is why you get the exception.
You can NOT use a trigger to perform validations such as those since the data will NEVER make it into the buffer the trigger uses.before it ever executes your code.
Similar Messages
-
Truncate Table before Insert--Performance
HI All,
This post is in focus of special requirement where a table is truncated before inserting records in the table.
Now, when a table is truncated the High Water Mark(HWK) is reset to lowest memory allocated for table in tablespace. After this, would insert with append can boost the performance of the insert query?
In simple insert query, the oracle engine consults the free list to look for free spaces.
But in insert with apppend, the engine starts above the HWM. And the argument is when truncate has been executes on table, would the freelist be used in simple insert.
I just need to know if there are any benefits of using append insert on truncated table or simple insert would be same in term of performance with respect to insert with append.
Regards
NitsHi,
if you don't need the data truncate the table. There is no negativ impact whether you are using an conventional path or a direct path insert.
If you use append less redo is written for the table if the table is in NOLOGGING mode, but redo is written for all indexes. I would recommand to create a full backup after that (if needed), because your table will not be recoverable after that (no REDO Information).
Dim -
Clob field not working in BEFORE INSERT trigger
Hello, everyone. I am trying to create a before insert trigger for a table (10g). I would like to create a value for a table field based on the xml query from a clob field. The table looks like this:
SQL> desc lac_costing_upload
Name Type Nullable Default Comments
UPLOAD_ID NUMBER Y
EMP_NUM VARCHAR2(20)
UPLOAD_DATE DATE Y
YEAR_MONTH VARCHAR2(10) Y
UPLOAD_TEXT CLOB Y
The trigger code looks like this:
create or replace trigger lac_cst_upl_yr_month
before insert on lac_costing_upload
for each row
declare
l_month varchar2(20);
l_year varchar2(20);
l_error_msg varchar2(255);
begin
SELECT XMLTYPE (:old.upload_text).EXTRACT('Oracle_Extract/Year/text()').getstringval() Extr_Year
, XMLTYPE (:old.upload_text).EXTRACT('Oracle_Extract/Month/text()').getstringval() Extr_Month
into l_year
, l_month
FROM dual;
:new.year_month := l_year || '.'
|| substr(l_month, 1, 3)
exception
when others then
l_error_msg := substr(sqlerrm, 1, 10);
:new.year_month := l_error_msg;
end lac_cst_upl_yr_month;
Here is a sample insert statement:
insert into lac_costing_upload lcu values(2006, '008925', sysdate, null
, '<Oracle_Extract>' || chr(10)
|| ' <Emp_Num>05417</Emp_Num>' || chr(10)
|| ' <Emp_Name>Fitzgerald</Emp_Name>' || chr(10)
|| ' <Year>2007</Year>' || chr(10)
|| ' <Month>May</Month>' || chr(10)
|| ' <Vehicle>1330</Vehicle>' || chr(10)
|| '</Oracle_Extract>'
My hope was to see '2007.May' in the year_month field. However, I'm getting 'ORA-06502:' instead. It looks like the value of :old.upload_text is null in the trigger.
Can anyone tell me what I'm doing wrong?
Thanks for any help.
--DaveThat's probably a really dumb error, but I don't work much with triggers.
It's working now.
Thanks for your help.
--Dave -
Check for required fields before locking subforms and submitting
Hello,
I have a 5-page form with many questions, to be completed by the original requestor and multiple approvers. What I'm trying to do is have the original requestor's Submit button on p. 3 lock the input on the first three pages, but first check if all those fields have some content. I currently have all the fields on pp. 1-3 set to "Required" in the object properties, but my script still locks them when there's is one empty one. Here's what I have:
//Lock portions of form
Page1.access = "readOnly"
Page2.access = "readOnly"
Page3.access = "readOnly"
//Save document, allow user to change name
app.execMenuItem("SaveAs");
//Submit via e-mail
Submit_REAL.event__click.submit.target = "mailto:[email protected]" +
"?subject=Subject text" +
"&body=Message";
Submit_REAL.execEvent("click");
The automatic check for required fields happens after the pages get locked. I would like the check to stop the process before it locks the pages. Is there any way to check all at once that all "Required" fields on those pages have some content before allowing the script to proceed? I know how to script it to manually check the 50 or so questions on those pages, but I would like to avoid that. Thanks for any help.There are a few problems that I can see from the start. First, your code is going to pick up EVERY node that exists on these pages. Some of those nodes will not have a rawValue, and some will not have an actual name. As an example, you can take your code and create a text field to dump all of the names of the nodes that you get when you pull in all of the nodes this way. Here's an example:
The result:
Now, the question is, do you have a consistent naming convention for your fields that might be empty? That could be text fields, radio button lists, etc. For instance, I always prefix the names of objects in order to more easily keep track of what they are in scripts. Since I'm doing that, I can check the name of the field for tf, nf, rbl, cb, or whatever I have included to make sure that I'm checking an actual field before I check for things like rawValue.
var nodeName = oNodes.item(nNodeCount).name;
if (nodeName.indexOf("tf")>-1 || nodeName.indexOf("rbl") > -1 || /*check other field types*/) {
//insert your code to check for empty answers here
As for your line 7 issue. The syntax problem is that you've put extra parentheses in your if statement. Take out the parentheses that are just before and after the or "||".
*This is my fourth attempt to reply. Something was going on with Adobe/Jive earlier, I suppose. -
Best Practice PK Generation: 'before insert on trig' vs. rolling yer own
Experts,
I have a form with the standard Create/Delete/Apply Changes buttons.
When someone hits "Create", I have a trigger that fires on the table as "before insert on". It hits a sequence to get a new primary key for the record which is about to be created.
Another way of doing it is to run a page-level PL/SQL computation, and get SEQUENCE_NAME.Nextval, and stuff it into the appropriate page-level item. "Create" will then fire the insert after this computation and it amounts to the same thing as the trigger.
Loaded question: Which way is better?
My DBA recommends to "roll my own" using the page-level computation. His reasoning is if my applications scale up to a lot of users running inserts at the same time, the trigger will be a bit of a drag.
On the other hand, I like having the trigger "on the database" and not having to worry much about it. It is one less thing that I have on my page.
DanI'm not the end-all be-all of Oracle expertise, so I
refer to those who are:
http://asktom.oracle.com/pls/asktom/f?p=100:11:0::::P1
1_QUESTION_ID:4343369880986#34562653805149
http://asktom.oracle.com/pls/asktom/f?p=100:11:0::::P1
1_QUESTION_ID:4343369880986#76218085672062
A couple links I could quickly find on the subject.
I'm sure there's plenty more out there.Taking Tom's answers out of context don't invalidate the problems of a trigger"less" approach.
As to the other concerns, personally I would argue
that a separation between application logic and GUI
shouldn't go so far as to remove all data management
concerns, such as using primary keys (and otherwise
indexed fields) to access data.Still, what happens if you want to user other methods of access, for example sqlldr/external tables, ODBC/.NET, etc.?
Also, I prefer to keep rogue applications/scripts
away from my data if possible :). Translated: Everyone has to incorporate sequences in any INSERT statement. For BULK inserts, this maybe the way to go, but you can always check if the PK column is NULL, which should give the trigger a bit of performance improvement.
But on the chance
that they do go selecting from incorrect sequences it
will be their own problem. Or your's if other applications start generating error messages.
It'll be refused insert
until it can (randomly, I don't care) provide a
unique value for that column. Yay for constraints!Finding the source of the problem might be where unnecessary work has to be put in.
I agree there are a few valid uses for such a
trigger, I've done it myself. But on the whole, it's
best to avoid it when possible.Can't follow your argument, really. Maybe another agree to disagree topic?
C. -
Apply validations on internal table fields before updating table
I have to upload data from a CSV file to R3 ztable, but before that I have to apply diffrent validations to check if fileds does not contaion invalid characters ....
eg
for a currency field I want to check if user has entered value in decimail format e.g 3.23, -22.33 etc but not like this 3..2, _+3.33, e3e& etc
How can I do this .....hi ,
There are lots of thread related to upload data .
you can search in SDN .
One method is to upload data in excel format and getting data in one internal table and then validatiing
before insert or update .
Moderator message - Please respect the 2,500 character maximum when posting. Post only the relevant portions of code
Regards
Deepak.
Edited by: Rob Burbank on Oct 3, 2010 3:36 PM -
Where in the Code can I Call a function Before Insert
Hi, using DWMX and VBSCRIPT with n MS Access table set on a
W2k3 server and ASP
I need to insert a value 'intGradID' from a function into a
hidden field 'hGradID' when the submit button (to insert a record
in an access database) is clicked (and before insert takes place as
this is the key field that I am adding).
I realise Javascript might be required (not too great with
Java) so any help please tell me where to put script/code and what
to put. Thanks.Why not just setup the field in the record to be
auto-incrementing? That way
on insert the next # in the series is assigned to the new
record. And even
if 2 people someone did it at exactly the same time, the
server takes care
of the collision.
"Dave(UK)" <[email protected]> wrote in
message
news:e9uakp$s11$[email protected]..
> Hi, using DWMX and VBSCRIPT on a W2k3 server and ASP
>
> I have an on-line application form for Graduates (bound
to Insert Into a
> table
> called graduates). On open of the page (at the top) I
have some some code
> to go
> look in the Graduates table for the last gradID No and
add 1 for this new
> Graduate and I set a session variab;e with the GradID
found and that value
> is
> the 'Initial Value' of a hidden field hGradID which is
inserted into
> GradID in
> the table on Submit, along with the other info. Works
Perfectly!! Until,
> that
> is, during the course of one Graduate registering,
another tries to do so
> ..
> both get the same gradID and the one who submits last
ends up with the
> error
> 'Dulicate in Key field '(ie GradID in the table). What I
got to work was
> to set
> up another table (GradOn) into which at the end of the
GradID+1 routine,
> the
> GradID was entered and when the form was submitted, it
ran a routine to
> delete
> the contents of GradOn. Then if the form was opened
again by another user,
> the
> first routine now was to check for a presence of a
record (any record) in
> the
> GradOn Table - if a record existed, it redirected to a
'Registration in
> Progress - Please try later page' ... again all worked
well, perfectly,
> until
> a. The user left the form open for hours
> b. The user used the browser to wuit the page instead of
the logoff which
> ran
> a routine to 'Delele * from GradOn' -
Resultset after insertion is the same before insertion
hi guys, i get an updatable resultset from a connection then used it to insert a new row but the result set doesn't chane after insertion, i mean the no of rows before insertion is the same after insertion and also the data, this is the code prove what i say
int currentRow = resultset.getRow();
display(resultset);
resultset.moveToInsertRow();
for (int i = 0; i < fields.size(); i++) {
updateCurrentRow(resultset, fields.getField(i));
resultset.insertRow();
display(resultset);the display function body is
int currentRow = res.getRow();
res.first();
while (true)
System.out.println("CountyCode= " + res.getInt(1));
System.out.println("CountyName= " + res.getString(2));
if (!res.next())
break;
res.absolute(currentRow);Please help me
N.B.
the type of resultset after creation it is res.getConcurrency() == ResultSet.CONCUR_UPDATABLE?????
Thanks for your effortsthnaks for your reply, but when i used
ownInsertsAreVisible() method; returned true, that is
mean that the driver and DB supports the updating of
reultset after insertion. but this is not real at my
case? that was strange. if you have any comment please
do,just checking the row is in fact being inserted into the database? i mean you can't see it right away but you can see it later right?
if the row is being inserted and the ownInsertsAreVisible() returns true then there are two possible scenarios.
1) the cursor type of your result set does not support that method, meaning the method is true in some cases but not yours... for example your query might have a join or something which makes it not possible for the result set do be fully cognizant of changes. and sometimes there are database specific cursors that have to specified as part of your query in a proprietary way to get the "right" cursor. you will need to investigate the docs for your database to figure out if any of this is true.
2) the meta data is lying. -
Regarding before insert and update trigger...Urgent!!
i have written a trigger to trim N upper the 1st field and trim N upper N replace period(.) for second field2 for future records.
When i compile, it says "complied with errors" is gives error as "insuffecient privlages"
Can anyone please figure out what problem is this??? And is my code correct?? if any changes to be done please let me know????
create or replace trigger TRG_test
before insert or update on test
for each row
declare
begin
:new.field1 := trim(upper(:new.field1));
:new.field2 := trim(upper(replace(:new.field2,'.' )));
end;
Urgent please!!!
Thank you in advance.The owner of the tables is User 2 and i am creating the trigger in user1 N i m calling this table from user2...as User2.TEST ...
User 1 as has previliges to acess the user 2 tables, since user2 tables are listed under user1 table section...
Do you system privilages????
I m using PL/SQL devloper tool.... -
How to delete the Table Contents before inserting records into SQL table ?
Hello Experts,
I have a scenario where in I have to Pick up some records from SAP RFC & insert into SQL table.
i know how to do this scenario but the proble with this is before inserting we first have to ZAP the SQL table & insert a new records. One more twist is The Triggering is happening from SAP side with Sender RFC. If this would have been from SQL Side i could have written a Stored Procedure/ Trigger & could have called this before the SENDER JDBC communciation channel picks up the Triggering event from SQL side.
So how to do this scenarioin XI, First deleting all the Records of SQL table & then inserting the new reocrds. without using the BPM.
Regards,
Umeshhi umesh,
you can achieve this by writing SQL query in message mapping level..
refer this link:
http://help.sap.com/saphelp_nw04/helpdata/en/b0/676b3c255b1475e10000000a114084/frameset.htm
regards. -
Hi,
Sorry, I am new to PDF Development. I tried creating PDF using Acrobat XI Pro. During creation, I have encountered issues in running custom JavaScript. The requirement is to validate all the required fields before saving the PDF. I tried using the following scripts to validate the said required fields. But, it's not working.
Option 1: If the field is null, a message box will appear.
if(this.getfield("textbox") = null){
app.alert("required");
else {app.execMenuItem("SaveAs");}
Option 2: If the field is required, a message box will appear.
var f = this.getField("textbox");
f.required = true;
if(f = true)
app.alert('required');
else
app.execMenuItem("SaveAs");
The scripts mentioned above are not working. I wanted to validate the required fields before saving the PDF.
In addition, I tried validating each field using the following script:
f = getField(event.target.name)
if (f.value.length == 0)
f.setFocus()
//Optional Message - Comment out the next line to remove
app.alert("This field is required. Please enter a value.")
When I open the PDF, the script is working. However, when the message box pops out, the "OK" button is not working as expected. The message box is not closing. I tried opening the form in a site in different Java versions (like 7-11 and 7-67). It's working in version 7-67. I tried upgrading the Java version from 7-11 to 7-67. Still, it doesn't work.
I would appreciate your feedback on this matter.If you set the fields as required, then when the user hits the print button you could run this script:
var txt = form1.execValidate();
if (txt == true){
print command
This code assumes that the root node of your form is form1. Also ensure you put a message into the Empty Message parameter for each field that you want to mark s required. -
Duplicate record check before inserting records
Hi All
I want to show an user friendly message instead of (oracle.jbo.TooManyObjectsException: JBO-25013: Too many objects match the primary key oracle.jbo.Key). So in my EO i have written the following code:
OADBTransaction transaction = getOADBTransaction();
Object[] empNumberKey = {value};
EntityDefImpl empDefinition =
XXXXempEOImpl.getDefinitionObject();
XXXXempEOImpl empNo=
(XXXXempEOImpl)empDefinition.findByPrimaryKey(transaction,
new Key(empNumberKey));
if (empNo != null) {
throw new OAAttrValException(OAException.TYP_ENTITY_OBJECT,
getEntityDef().getFullName(),
getPrimaryKey(), "CompanyNumber",
value, "AK",
"FWK_TBX_T_EMP_ID_UNIQUE");
setAttributeInternal(COMPANYNUMBER, value);
My observation is when duplicate empNumber is passed as '0011' then the error message is not thrown.But if i pass duplicate empNumber like '5411' error is thrown. So does it mean new Key(empNumberKey)) chops off leading 0's. Please note that in database the values are stored as '0011'. Pleasre advice. The validation fails only when value is having leading 0's.You need to create a select command before Insert and check for the result returned after executing ExecuteScalar, this will return the records count to decide whether to insert or not,
Check the below example:
http://stackoverflow.com/questions/15320544/how-to-check-if-record-exists-if-not-insert-using-vb-net
Fouad Roumieh -
INSERTstatement is not working if there is a before insert trigger
INSERTstatement is not working if there is a before insert trigger on that table. That trigger contains an insert to another table which having the main table reference.
Let us say, for example there a table named 'EMP_DEPT' and there is a before insert trigger on this table.
In this trigger inserting a record in to another table named 'AUDIT_EMP' and in this table using EMP_Dept primary key as foreign key.
Table EMP_DEPT is having the below columns:
EMP_DEPT_SYS_ID
EMP_DEPT_NO
DEP_NAME etc..
Table AUDIT_EMP is having the below columns:
AUDIT_EMP_SYS_ID
EMP_DEPT_SYS_ID
AUDIT_NO etc..
the code in the trigger is
INSERT INTO audit_emp
(audit_emp_sys_id, emp_dept_sys_id, audit_no
VALUES (audit_emp.NEXTVAL, :new EMP_DEPT_SYS_ID, '1101'
Now when you execute the insert query like:
INSERT INTO emp_dept
(emp_dept_sys_id, emp_dept_no, dep_name
VALUES (EMP_DEPT.nextval, 1001, 'Dep-1'
It is giving the error saying 'Integrity constraint error, parent key not found' from the trigger.
But, when you modify the above insert query like the below then it is working.
INSERT INTO emp_dept
(emp_dept_sys_id, emp_dept_no, dep_name
SELECT EMP_DEPT.nextval, 1001, 'Dep-1'
FROM DUAL;
I am using Oracle 10g.
Why the insert into values is not working. Is there any commit transaction sequence change? Any idea please?
Edited by: user6475632 on Sep 16, 2009 7:08 AMObviously the code you posted can not work.
You are inserting the detail record (the audit record) before the master record, where it should have been after. IMO, you should fire the trigger AFTER INSERT for each row.
If that still doesn't work, you need to change the foreign key constraint into a deferred constraint, which is evaluated at commit, instead of immediately. The SQL reference manual has further info on this.
'Oracle 10g' is considered a marketing label here, not a -4 digit- version.
Sybrand Bakker
Senior Oracle DBA -
Calling function in before insert trigger
HELLO,
**TRIGGER IS NOT DISPLAYING THE DATA ACCURATELY**
**PLZ HELP ITS URGENT...**
THE CODE IS BELOW.....
create or replace TRIGGER GENSTUDYID
BEFORE INSERT
ON ER_PATPROT
REFERENCING NEW AS NEW OLD AS OLD
FOR EACH ROW
DECLARE
lPatStudyID varchar2(30);
lSiteCode number(10);
lStudyCode number(10);
lpk_patprot Number(10);
lpatprot_enroldt date;
lFK_PER number(20);
lIPADD varchar2(15);
lfk_protocol number(20);
llast_modified_by number;
lgencal_status number;
BEGIN
lSiteCode := :New.fk_site_enrolling;
lStudyCode := :new.fk_study;
lpk_patprot := :new.pk_patprot;
lpatprot_enroldt := :new.patprot_enroldt;
lFK_PER := :new.fk_per;
lIPADD :=NULL;
lPatStudyID:=GenerateStudyID(lSiteCode,lStudyCode,lFK_PER);
IF lPatStudyID IS NOT NULL then
:NEW.patprot_patstdid := lpatstudyid;
END IF;
END;
-----------FUNCTION CODE STARTS
create or replace
function GenerateStudyID (sitecode number,studycode number,pid number) RETURN VARCHAR IS
lfield_name varchar2(10);
lfield_format varchar2(10);
lfield_length number(2);
lfield_deftext varchar2(500);
lparam1 varchar2(30):=sitecode;
lparam2 varchar2(30):=studycode;
lresult varchar2(30);
lstudyid varchar2(30);
lPATPROT_PATSTDID varchar2(20);
CURSOR studyid_def_cur is select field_name, field_format, field_length, field_deftext from bayatree.studyid_definition
where study_code = studycode and site_code=sitecode order by field_seqno;
CURSOR patprot_patstdid_cur is select PATPROT_PATSTDID from eres.er_patprot where fk_study=studycode and fk_per=pid;
BEGIN
lstudyid := NULL;
dbms_output.put_line('studycode: '||studycode);
dbms_output.put_line('pid; '||pid);
FOR disp_studyid in patprot_patstdid_cur
LOOP
lPATPROT_PATSTDID:=disp_studyid.PATPROT_PATSTDID;
dbms_output.put_line('lPATPROT_PATSTDID: '||lPATPROT_PATSTDID);
END LOOP;
IF lPATPROT_PATSTDID IS NULL THEN
OPEN studyid_def_cur;
LOOP
FETCH studyid_def_cur INTO lfield_name, lfield_format, lfield_length, lfield_deftext;
EXIT WHEN studyid_def_cur%NOTFOUND;
lfield_deftext:= replace(lfield_deftext,'param1',lparam1);
lfield_deftext:= replace(lfield_deftext,'param2',lparam2);
if (instr (lfield_deftext, 'select',1) > 0) then
execute immediate lfield_deftext into lresult;
else
execute immediate lfield_deftext;
lresult := null;
end if;
if lfield_format is not null and lresult is not null and lfield_length is not null then
lresult := lpad(lresult, lfield_length, 0);
end if;
if lfield_name is not null and lresult is not null then
lstudyid := lstudyid || lresult;
end if;
END LOOP;
return (lstudyid);
ELSE
lstudyid:=lPATPROT_PATSTDID;
Dbms_output.put_line('Study Id: '||lstudyid);
return (lstudyid);
END IF;
END;Your post is not quiet readable, please include your program in tags, Include sample data and sample output, table and other objects creation and insert scripts.
What error are you getting anyway post the Oracle error code
SS -
Before insert Trigger and SQL Loader
Hi,
I have a table with a BEFOR insert on each row trigger . I am loading the data to that table using sqlloader and I want my trigger to fire for each row. But the trigger is firing only for alternate rows.
body of trigger as follows.
select max(pd_id) into VarVal from <table name> where tar_id=:new.tar_id;
select pd_id+1 into :new.pd_id from dual;
if I remove the first select statement from my trigger , then it is firing for all the rows. But the removel of first select statement will not satisfy my requirements.
So please suggest me how can I achieve this.[url http://forums.oracle.com/forums/thread.jspa?threadID=587783&tstart=0]duplicate thread
Maybe you are looking for
-
Podcast audio not showing up on site or iTunes
I've been searching for the answer to this for hours now. I can create a podcast via GarageBand, sent it to iWeb, and publish my site, but when I go to the page that has the blog entry for the Podcast, I can't see/hear the audio! I see the picture th
-
JFileChooser under Java Web Start
I have a problem when using a JFileChooser - object in a Web Start Application: I always get the message that there is no disk in drive A:, even if I create the JFileChooser object with a default path String in the constructor JFileChosser fileChoose
-
How to create reports with the prompts like the pre-defined reports ?
We are analyzing pre-defined report: Historical Pipeline Analysis. When executed we can see the prompts for Pipeline Fiscal Quarter and Pipeline Fiscal Year. If we open this analysis I cannot see how this prompt have been built. If I save this pre-de
-
I installed photoshop cc 2014, but Camera Raw remains on Version 8.0. Update to 8.5 does not work.
-
please i need your help