Change Character Allowance - oracle

I have a VARCHAR field that only allows 12 characters max. How do I change character allowance to 9 or 15 for example?
Google succeeds in telling me what the max number of characters in VARCHAR in any given version of Oracle database. I know, I get that. I just want to ALTER the column character allowance within that range.

alter table table_name MODIFY (column_to_change varchar(new size))

ALTER TABLE tbl_name MODIFY col_name column_definition;
So if you have:
CREATE TABLE table_name (
value VARCHAR2(12)
);
Then you can do:
ALTER TABLE table_name MODIFY value VARCHAR2(15 BYTE);
and the column will have a capacity of 15 bytes.
Or:
ALTER TABLE table_name MODIFY value VARCHAR2(9 CHAR);
and the column will have a capacity of 9 characters.

Related

How does Number data type work in Oracle 21c?

I created a table like this:
CREATE TABLE table(
id INTEGER GENERATED ALWAYS AS IDENTITY,
nome VARCHAR2(100 CHAR)
)
ALTER TABLE table ADD CONSTRAINT table_pk PRIMARY KEY (ID);
CREATE UNIQUE INDEX TABLE_UNIQ_IDX ON TABLE(NOME ASC);
ALTER TABLE table ADD (PERC NUMBER(1, 2) NOT NULL);
Then I tried to write 2 records on it:
INSERT INTO TABLE(NOME,PERC)VALUES('a',0.8);
INSERT INTO TABLE(NOME,PERC)VALUES('b',0.2);
Then I received this error:
ORA-01438: valor maior que a precisão especificada usado para esta coluna
Translated:
ORA-01438: value larger than specified precision allows for this column
I tried select cast (0.8 as number(1,1)) from dual; and it worked but when I tried select cast (0.8 as number(1,2)) from dual; I received the same error.
I then tried select cast (0.81 as number(1,2)) from dual; and received the same ORA-01438.
I changed my field to number(1,1), no big deal, but how does this "Number" data type work?
Shouldn't select cast (0.81 as number(1,2)) from dual; have worked?
Why does select cast (0.81 as number(2,2)) from dual; work and
select cast (0.81 as number(2,3)) from dual; does not?
Thanks for any help
If you have NUMBER(precision, scale) then precision is the number of digits and scale is the number of decimal places.
So, NUMBER(1, 2) has a single digit and 2 decimal places. The minimum value it can store is -0.09 and the maximum it can store is +0.09.
NUMBER(2,2) works as it stores 2 digits in 2 decimal places (from -0.99 to +0.99).
NUMBER(2,3) does not work as it stores 2 digits in 3 decimal places (from -0.099 to +0.099).
What you said, is that perc column should accept numeric values whose length is 1, and out of that 1, you want to keep 2 decimal places. That won't work.
SQL> create table test (perc number(1, 2));
Table created.
SQL> insert into test values (0.8);
insert into test values (0.8)
*
ERROR at line 1:
ORA-01438: value larger than specified precision allowed for this column
Perhaps you meant to put it vice versa?
SQL> alter table test modify perc number(2, 1);
Table altered.
SQL> insert into test values (0.8);
1 row created.
SQL>

How to increment the value of the unique constraint column value in ORACLE

How to increment the value of the unique constraint column value in ORACLE, in the select statement.
For example, in a table 'BILLING_TABLE' - column BLNG_Sk is the unique key (Autoincremented).
So while inserting a new record into the BILLING_TABLE, for the column BLNG_SK we need to give the value (Which is the increment by 1 from the present max value.)
For example, if BLNG_SK max value is 12321.
new record should be 12322.
how to achieve this in Oracle?
Oracle has a SEQUENCE object which provides the functionality you require.
You create one using the CREATE SEQUENCE SQL statement.
The Oracle documentation provides all the required information and the documentation is available via Oracle's Web site.
Assuming you are on Oracle 12.1 or later, define it as an identity column and do not pass any value when inserting:
create table testtable
( test_id number generated always as identity
constraint testtable_pk primary key
, othercol varchar2(10) );
insert into testtable (othercol) values ('Demo');
select * from testtable;
TEST_ID OTHERCOL
---------- ----------
1 Demo
insert into testtable (othercol) values ('Demo #2');
select * from testtable;
TEST_ID OTHERCOL
---------- ----------
1 Demo
2 Demo #2
Try creating a sequence and a trigger. This is the case when you provide the value manually.
CREATE SEQUENCE dept_seq START WITH 12322;
Trigger definition:
CREATE OR REPLACE TRIGGER dept_bir
BEFORE INSERT ON BILLING_TABLE
FOR EACH ROW
BEGIN
SELECT dept_seq.NEXTVAL
INTO :new.id
FROM dual;
END;
/

Oracle index maximum key length exceeded

I get error ORA-01450: maximum key length (6398) exceeded as I try creating below index
CREATE INDEX FORENAME_SURNAME ON CARD_HOLDER( REGEXP_REPLACE (UPPER( FORENAME ),'\\s|-|_|\\.|\\:|\\,',''), REGEXP_REPLACE (UPPER( SURNAME ),'\\s|-|_|\\.|\\:|\\,','') );
Error code is fair clear but my columns are 100Bytes each so how is possible index exceed the max??
And db_block_size = 8192 not 6398.
Below columns definition
CREATE TABLE CARD_HOLDER
( "CARD_HOLDER_ID" NUMBER NOT NULL ENABLE,
"TITLE" VARCHAR2(10 BYTE),
"FORENAME" VARCHAR2(100 BYTE),
"SURNAME" VARCHAR2(100 BYTE) NOT NULL ENABLE,
)
You can try using this with concatenation instead of two different columns. However this is only a workaround and might not be useful unless you are using the query as such with concatenation.
CREATE INDEX forename_surname ON
card_holder ( regexp_replace(upper(forename),'\\s|-|_|\\.|\\:|\\,','')
|| regexp_replace(upper(surname),'\\s|-|_|\\.|\\:|\\,','') );
The length of 6398 is the maximal length of the index key in a 8KB block size tablespace as the block must contain the key plus some overhead.
Why are you getting the error for your 100 byte columns can be easily demonstrated.
Let's define a view with your additional columns
create view ch2 as
select c.*, REGEXP_REPLACE (UPPER( FORENAME ),'\\s|-|_|\\.|\\:|\\,','') for2,
REGEXP_REPLACE (UPPER( SURNAME ),'\\s|-|_|\\.|\\:|\\,','') sur2
from CARD_HOLDER c
If you check the data types of the new columns you see
select COLUMN_NAME, DATA_TYPE, DATA_LENGTH
from user_tab_columns where table_name = 'CH2' and column_name in ('FOR2','SUR2');
COLUMN_NAME, DATA_TYPE, DATA_LENGTH
FOR2 VARCHAR2 4000
SUR2 VARCHAR2 4000
Oracle expects the result of the regexp_replace could have the maximal length of 4000, which end in total of 8000.
So what to do?
Ask Tom has a nice overview of workarounding the problem with key length.
Among others solution you could define a tablespace with a larger block size for your index.
You may also step back and use TRANSLATE (or REPLACE) to remove the unwanted characters such as
TRANSLATE(upper(FORENAME),'x'||CHR(9)||CHR(10)||CHR(11)||CHR(12)||CHR(13)||' -_.:,','x')
Here Oracle asumes the result will be only 400 charater long so there will be no problem with the index key.

Trigger required to insert data [duplicate]

This question already has answers here:
Using sequential values for the primary key in an INSERT query
(2 answers)
Closed 9 years ago.
I am trying to load a column with unique sequence number each time a row of data is insrerted in the table.How can this be achieved?
You can create a Sequence, and then use the sequence nextval in your insert statements for the column which you want to have sequential incremented value.
CREATE SEQUENCE seq
INCREMENT BY 1
START WITH 1
NOMAXVALUE
NOCYCLE
CACHE 10;
INSERT INTO tab VALUES (seq.nextval, col1, col2, col3);
there is nothing like "auto_increment" or "identity" in Oracle,
but if you want auto increment in your column value you can use Sequence for the this.
after creating sequence you can use After Insert Trigger to insert identical value.
here is trigger example...
CREATE OR REPLACE TRIGGER dep_ins_trig
BEFORE INSERT ON <table_name>
FOR EACH ROW
BEGIN
SELECT dept_seq.NEXTVAL
INTO :new.id
FROM dual;
END;
/
This is achieved by Trigger and Sequence when you want serialized number that anyone can easily read/remember/understand. But if you don't want to manage ID Column (like emp_id) by this way, and value of this column is not much considerable, you can use SYS_GUID() at Table Creation to get Auto Increment like this.
CREATE TABLE <table_name>
(emp_id RAW(16) DEFAULT SYS_GUID() PRIMARY KEY,
name VARCHAR2(30));
Now your emp_id column will accept "globally unique identifier value".
you can insert value in table by ignoring emp_id column like this.
INSERT INTO <table_name> (name) VALUES ('name value');
So, it will insert unique value to your emp_id Column.

How to generate alphanumeric id in Oracle

In my vb application I want an autogenerated id of alphanumeric characters, like prd100. How can I increment it using Oracle as backend?
Any particular reason it needs to be alphanumeric? If it can just be a number, you can use an Oracle sequence.
But if you want just a random string, you could use the dbms_random function.
select dbms_random.string('U', 20) str from dual;
So you could probably combine these 2 ideas (in the code below, the sequence is called oid_seq):
SELECT dbms_random.string('U', 20) || '_' || to_char(oid_seq.nextval) FROM dual
There are two parts to your question. The first is how to create an alphanumeric key. The second is how to get the generated value.
So the first step is to determine the source of the alpha and the numeric components. In the following example I use the USER function and an Oracle sequence, but you will have your own rules. I put the code to assemble the key in a trigger which is called whenever a row is inserted.
SQL> create table t1 (pk_col varchar2(10) not null, create_date date)
2 /
Table created.
SQL> create or replace trigger t1_bir before insert on t1 for each row
2 declare
3 n pls_integer;
4 begin
5 select my_seq.nextval
6 into n
7 from dual;
8 :new.pk_col := user||trim(to_char(n));
9 end;
10 /
Trigger created.
SQL>
The second step requires using the RETURNING INTO clause to retrieve the generated key. I am using SQL*PLus for this example. I confess to having no idea how to wire this syntax into VB. Sorry.
SQL> var new_pk varchar2(10)
SQL> insert into t1 (create_date)
2 values (sysdate)
3 returning pk_col into :new_pk
4 /
1 row created.
SQL> print new_pk
NEW_PK
--------------------------------
APC61
SQL>
Finally, a word of warning.
Alphanumeric keys are a suspicious construct. They reek of "smart keys" which are, in fact, dumb. A smart key is a value which contains multiple parts. At somepoint you will find yourself wanting to retrieving all rows where the key starts with 'PRD', which means using SUBSTR() or LIKE. Even worse someday the definition of the smart key will change and you will have to cascade a complicated update to your table and its referencing foreign keys. A better ides is to use a surrogate key (number) and have the alphanumeric "key" defined as separate columns with a UNIQUE composite constraint to enforce the business rule.
SQL> create table t1 (id number not null
2 , alpha_bit varchar2(3) not null
3 , numeric_bit number not null
4 , create_date date
5 , constraint t1_pk primary key (id)
6 , constraint t1_uk unique (alpha_bit, numeric_bit)
7 )
8 /
Table created.
SQL>

Resources