How to change the table name during the runtime - oracle10g

I have the following,
create table ssrr_emp(
Emp_name varchar2(25),
Emp_city varchar2(10),
Emp_id number(2)
);
/
create table ssrr_empsal(
sal_grade char(1),
salary number(7,2),
Commission number(5)
);
/
In the above code,the table names are prefixed with ssrr i.e ssrr_emp and ssrr_empsal,
Here my question is when I am executing the above code
I need to prefix the table name with er i.e er_emp and er_empsal.
I mean during the runtime it should ask the name to enter only for ssrr,
and
if i enter er then the tables should be created in the name er_emp and er_empsal.

If you're using SQL*Plus, you can use substitution variables with &, e.g.:
create table &&PREFIX._emp(
Emp_name varchar2(25),
Emp_city varchar2(10),
Emp_id number(2)
);
/
create table &&PREFIX._empsal(
sal_grade char(1),
salary number(7,2),
Commission number(5)
);
/
When you run the script, it will prompt you for the value:
Enter value for prefix:

Related

(DB2) How to alter a existing table ID to use increment function?

I tried to modify an existing table primary key but fail. What should I correct in my statement?
For example, I have a existing patient table
CREATE TABLE Patient
( pat_id char(5) NOT NULL PRIMARY KEY,
...
);
and some data is inserted into the table
PAT_ID|PAT_NAME |PAT_GENDER|PAT_BD|PAT_IC |PAT_MOBILE |PAT_ADDR |PAT_ALLERGY|
------+------------+----------+------+--------------+-----------+------------------------+-----------+
P0001 |John Smith |Male |A+ |770305021234 |019-3652365|123 Taman Muda, Selangor|none |
P0002 |Jane Doe |Female |B- |820205191123 |012-3654789|456 Taman Tea, WPKL |peanuts |
...
P0009 |Natalie Lim |Female |A- |851217145682 |012-6322565|898 Taman Umum, WPKL |none |
P0010 |Kelly Tan |Female |O+ |020408141234 |019-1212556|880 Taman Raman, WPKL |none |
Here the question, since the id is a combination of char"P" follow but 4 digit increment, so i created a function as below:
CREATE FUNCTION patID_increment ()
RETURNS CHAR(5)
LANGUAGE SQL
BEGIN
DECLARE new_pat_id CHAR(5);
DECLARE current_id INT;
SELECT CAST(MAX(SUBSTR(pat_id, 2)) AS INT) INTO current_id FROM patient;
SET new_pat_id = 'P'||RIGHT('0000'||CAST(current_id + 1 AS VARCHAR(4)),4) ;
RETURN new_pat_id;
END
Yes, the function successfully execute and return "P0011" when I execute statement SELECT patID_increment() FROM SYSIBM.SYSDUMMY1;
But I fail to alter existing pat_id column, I had tried:
ALTER TABLE patient
ALTER COLUMN pat_id SET DEFAULT patID_increment()
ALTER TABLE PATIENT
MODIFY COLUMN pat_id CHAR(5) NOT NULL DEFAULT patID_increment();
but end up giving me error,
SQL Error [42894]: DEFAULT value or IDENTITY attribute value is not valid for column "PAT_ID" in table "DB2ADMIN.PATIENT". Reason code: "7".. SQLCODE=-574, SQLSTATE=42894, DRIVER=4.26.14
SQL Error [42601]: An unexpected token "MODIFY" was found following "ER TABLE PATIENT ". Expected tokens may include: "ADD".. SQLCODE=-104, SQLSTATE=42601, DRIVER=4.26.14
How can I alter the primary key column without remove the data or the table in db2?
(The table having connection with other table)
Use sequence + trigger instead.
MAX calculation for next value is very inefficient.
CREATE TABLE Patient
( pat_id char(5) NOT NULL PRIMARY KEY
, pat_name varchar (50)
);
INSERT INTO PATIENT VALUES ('P0001', 'John Smith'), ('P0010', 'Jane Doe');
CREATE SEQUENCE PATIENT_SEQ AS DEC (4) START WITH 11;
CREATE TRIGGER PATIENT_BIR
BEFORE INSERT ON PATIENT
REFERENCING NEW AS N
FOR EACH ROW
SET PAT_ID = 'P' || DIGITS (NEXTVAL FOR PATIENT_SEQ);
INSERT INTO PATIENT (PAT_NAME)
VALUES
('Natalie Lim')
, ('Kelly Tan');
SELECT * FROM PATIENT;
PAT_ID
PAT_NAME
P0001
John Smith
P0010
Jane Doe
P0011
Natalie Lim
P0012
Kelly Tan
fiddle

Redshift - inserting into identity column

I have created a table as mentioned below.
create table employee (
surrogate_key bigint IDENTITY(1,1),
first_name varchar(200),
last_name varchar(200),
phone_number varchar(200),
creditcard_number bigint
)
insert into employee values
('gaurang', 'shah', '356-776-4456', '4716973408090483')
However, following code is giving error.
Error
[Code: 500310, SQL State: 0A000] [Amazon](500310) Invalid operation: cannot set an identity column to a value;
insert into employee(first_name,last_name,phone_number,creditcard_number)
values('gaurang', 'shah', '356-776-4456', 4716973408090483)
You have to specify column names when identity column present in the table
One more option is define surrogate key with default like this
surrogate_key bigint generated by default as IDENTITY(1,1),
Then run this query
insert into employee1
values(default,'gaurang', 'shah', '356-776-4456', 4716973408090483)

How can i create auto increment column to my existing column?

I am working with Oracle 12c in which I have below table structure:-
CREATE TABLE patients (
patient_id Integer NOT NULL,
customer_id Integer NOT NULL,
title varchar(5) NOT NULL,
fname varchar(125) NOT NULL,
lname varchar(125) NOT NULL,
dob date NOT NULL,
is_medical_card NUMBER(1) NOT NULL CHECK (is_medical_card IN (0,1)),
scheme_number Integer NOT NULL,
status varchar(50) NOT NULL,
created_on date NOT NULL,
last_update_date date NOT NULL,
consent_flag NUMBER(1) NOT NULL CHECK (consent_flag IN (0,1)),
relationship varchar(50) NOT NULL
);
Where patient_id is my primary key so now I want to make it auto increment as well so please let me how can I do this so make it auto increment.
Thanks!
Need to create auto increment to existing column.
You might want to use Identities - Creating a table with an Identity gives you the chance to omit the ID values and let Oracle use a sequence on your desired column:
1. Let's Create the Table:
CREATE TABLE identities (
id NUMBER GENERATED BY DEFAULT ON NULL AS IDENTITY,
description varchar2(100) NOT NULL
);
Table created.
2. You'll want to create a primary key to ensure uniqueness:
alter table identities add constraint id_pk primary key (ID);
Table altered.
3. Let's insert some data in different ways:
INSERT INTO identities (description)
VALUES('Insert Description omitting ID');
1 row created.
INSERT INTO identities (id,description)
VALUES(NULL,'Insert with explicit NULL value');
1 row created.
4. Save the work done
commit;
Commit complete.
5. Check the results
select * from identities;
ID DESCRIPTION
---------- ---------------------------------------------
1 Insert Description omitting ID
2 Insert with explicit NULL value
As you can see we dind't specify any number for the ID, but the Identity on the ID column did for us
Note: Mind that you can manually insert an ID, but this will mess up with the Identity as it'll normally do with a standard Sequence:
INSERT INTO identities (id,description)
VALUES(3,'Manually insert an ID value');
1 row created.
INSERT INTO identities (description)
VALUES('Test Nextval');
INSERT INTO identities (description)
*
ERROR at line 1:
ORA-00001: unique constraint (XXX.ID_PK) violated
This error, because it tries to insert a '3' into the ID that was manually inserted with the statement before.
Check the table:
select * from identities;
ID DESCRIPTION
---------- ---------------------------------------------
1 Insert Description omitting ID
2 Insert with explicit NULL value
3 Manually insert an ID value
Re-Run the "NEXTVAL" insert:
INSERT INTO identities (description)
VALUES('Test Nextval');
1 row created.
Re-Check the table:
select * from identities;
ID DESCRIPTION
---------- ---------------------------------------------
1 Insert Description omitting ID
2 Insert with explicit NULL value
3 Manually insert an ID value
4 Test Nextval
Hope this Helps.

Postgresql - retrieving referenced fields in a query

I have a table created like
CREATE TABLE data
(value1 smallint references labels,
value2 smallint references labels,
value3 smallint references labels,
otherdata varchar(32)
);
and a second 'label holding' table created like
CREATE TABLE labels (id serial primary key, name varchar(32));
The rationale behind it is that value1-3 are a very limited set of strings (6 options) and it seems inefficient to enter them directly in the data table as varchar types. On the other hand these do occasionally change, which makes enum types unsuitable.
My question is, how can I execute a single query such that instead of the label IDs I get the relevant labels?
I looked at creating a function for it and stumbled at the point where I needed to pass the label holding table name to the function (there are several such (label holding) tables across the schema). Do I need to create a function per label table to avoid that?
create or replace function translate
(ref_id smallint,reference_table regclass) returns varchar(128) as
$$
begin
select name from reference_table where id = ref_id;
return name;
end;
$$
language plpgsql;
And then do
select
translate(value1, labels) as foo,
translate(value2, labels) as bar
from data;
This however errors out with
ERROR: relation "reference_table" does not exist
All suggestions welcome - at this point a can still alter just about anything...
CREATE TABLE labels
( id smallserial primary key
, name varchar(32) UNIQUE -- <<-- might want this, too
);
CREATE TABLE data
( value1 smallint NOT NULL REFERENCES labels(id) -- <<-- here
, value2 smallint NOT NULL REFERENCES labels(id)
, value3 smallint NOT NULL REFERENCES labels(id)
, otherdata varchar(32)
, PRIMARY KEY (value1,value2,value3) -- <<-- added primary key here
);
-- No need for a function here.
-- For small sizes of the `labels` table, the query below will always
-- result in hash-joins to perform the lookups.
SELECT l1.name AS name1, l2.name AS name2, l3.name AS name3
, d.otherdata AS the_data
FROM data d
JOIN labels l1 ON l1.id = d.value1
JOIN labels l2 ON l2.id = d.value2
JOIN labels l3 ON l3.id = d.value3
;
Note: labels.id -> labels.name is a functional dependency (id is the primary key), but that doesn't mean that you need a function. The query just acts like a function.
You can pass the label table name as string, construct a query as string and execute it:
sql = `select name from ` || reference_table_name || `where id = ` || ref_id;
EXECUTE sql INTO name;
RETURN name;

insert into and select

how would the query on:
Update the field total_horas with the hours worked on each project
I have:
insert into proyecto(total_horas)
select trabaja.nhoras
from trabaja;
But it's trying to insert in the first firld of "proyecto" instead on the field "total_horas"
my table:
CREATE TABLE proyecto (
cdpro CHAR(3) NOT NULL PRIMARY KEY,
nombre VARCHAR(30),
coddep CHAR(2),
FOREIGN KEY (coddep)
REFERENCES departamento(cddep)
ON DELETE CASCADE
);
also altered with: alter table proyecto ADD total_horas char ;
You have to put a where condition in select statement.And please elaborate you question. trabaja.nhoras is the column name and you are selecting it from table trabaja
Example:
INSERT INTO proyecto
(total_horas)
SELECT trabaja.nhoras
FROM trabaja
WHERE 'condition' = 'some condition';