how to update id from one table to another - java

I have two tables:
TABLE1 has columns(id,name,password),
TABLE2 has columns(id,salary,dept).
id in table1 is auto-generated sequence number. Data is added using java form. I wanted to show table1 id in table2 along with other details.
create or replace PROCEDURE PRO5(y in varchar,z in varchar,x in varchar,
c in varchar,d in varchar,b in number, j in number)
as BEGIN
insert into emp_general(username,email,password) values(y,z,x);
insert into SALARY_DET(username ,salary,company,dept) values(y,c,d,b);
set j := INSERT INTO salary_det(ID) SELECT ID FROM emp_general;
END;

Try this,
select #Id = convert(int,scope_identity());
For Oracle
SET LID = LAST_INSERT_ID();

Related

Inserting value in middle table in sqlite

I am trying to insert a value in a middle table, which is created by having two other tables relationship many to many. So this middle table has 2 foreign keys(idProduct and idWarehouse), one for each table and an additional row(storage). So I have trouble inserting in this third row.
It gives this error:
Result: near "SELECT": syntax error
At line 1:
INSERT INTO ProductsInWarehouse (idProduct, idWarehouse, storage)
VALUES
(SELECT
This is my code:
INSERT INTO ProductsInWarehouse (idProduct, idWarehouse, storage)
VALUES
(SELECT id FROM Products
WHERE nameProduct = 'cheese',
SELECT id FROM Warehouse
WHERE nameWarehouse = 'Vegas',
'10')
Each of the queries must be enclosed inside parantheses:
INSERT INTO ProductsInWarehouse (idProduct, idWarehouse, storage) VALUES
(
(SELECT id FROM Products WHERE nameProduct = 'cheese'),
(SELECT id FROM Warehouse WHERE nameWarehouse = 'Vegas'),
'10'
);
This will work if theses queries return always only 1 row, so both columns nameProduct and nameWarehouse must be unique.
The statement can also be written without the VALUES clause, with SELECT:
INSERT INTO ProductsInWarehouse (idProduct, idWarehouse, storage)
SELECT
(SELECT id FROM Products WHERE nameProduct = 'cheese'),
(SELECT id FROM Warehouse WHERE nameWarehouse = 'Vegas'),
'10';

ANDROID STUDIO / SQLiteLog: (1) near "LIMIT": syntax error

I am trying to delete the duplicates that I am getting in my database using DELETE function of my SQL with LIMIT 1 but it is showing me the "LIMIT" syntax error .
myDatabase.execSQL("CREATE TABLE IF NOT EXISTS users (name VARCHAR , age INT(3))");
myDatabase.execSQL("INSERT INTO users (name, age) VALUES ('Vaishant', 21)");
myDatabase.execSQL("INSERT INTO users (name, age) VALUES ('Tommy',4)");
myDatabase.execSQL("DELETE FROM users WHERE name = 'Vaishant' LIMIT 1");
Can someone tell me why I am getting this error and how to correct it ?
SQLite does not support LIMIT in a DELETE statement.
Use a subquery that returns the rowid of a row that contains the name that you search for:
String sql = "DELETE FROM users WHERE rowid = (SELECT rowid FROM users WHERE name = 'Vaishant' LIMIT 1)";
myDatabase.execSQL(sql);
If you want to delete the duplicate names and keep only 1, then you can do this:
DELETE FROM users
WHERE NOT EXISTS (SELECT 1 FROM users u WHERE u.name = users.name AND u.rowid < users.rowid)
or:
DELETE FROM users
WHERE rowid NOT IN (SELECT MIN(rowid) FROM users GROUP BY name)
In your delete statement you are using limit with Delete query. You should use it as below:
First add id column as primary key in your table
myDatabase.execSQL("CREATE TABLE IF NOT EXISTS users (ID INTEGER PRIMARY KEY AUTOINCREMENT, name VARCHAR , age INT(3))");
change the query of delete as below
myDatabase.execSQL("DELETE FROM users
WHERE id IN
(SELECT id FROM
(SELECT id,
ROW_NUMBER() OVER (PARTITION BY name ORDER BY name) AS row_num FROM users )t
WHERE row_num > 1)");

Query for many to many relationship database table

I have list of data and a table like below.
Data : {ABC111,ABC112,ABC113,111111,111112,111113}
Table:
Column 1 Column 2
ABC111 ABC115
ABC115 111333
111111 ABC112
111111 111112
ABC123 111113
111113 ABC113
My result should be like below
Result : {ABC115,111333,111113,ABC113,ABC123,ABC112,111112}
Explanation:
Data - ABC111 is associated to ABC115 which is also associated to 111333. Hence the result is ABC115,111333.
Similarly, ABC113 is associated to 111113 which is also associated to ABC123. Result = 111113,ABC123.
Is it possible to implement the above using a query. Looking for Prepared statement to which I will pass the Data that I mentioned above.
Try this:-
/*CREATING RECORDS FOR THE MAIN TABLE*/
CREATE TABLE TABLES(Column1 text, Column2 text);
INSERT INTO TABLES VALUES('ABC111','ABC115');
INSERT INTO TABLES VALUES('ABC115','111333');
INSERT INTO TABLES VALUES('111111','ABC112');
INSERT INTO TABLES VALUES('111111','111112');
INSERT INTO TABLES VALUES('ABC123','111113');
INSERT INTO TABLES VALUES('111113','ABC113');
COMMIT;
/*CREATE LIST TO BE SUPPLIED*/
CREATE TABLE LIST(Column1 text);
INSERT INTO LIST VALUES('ABC111');
INSERT INTO LIST VALUES('ABC112');
INSERT INTO LIST VALUES('ABC113');
INSERT INTO LIST VALUES('111111');
INSERT INTO LIST VALUES('111112');
INSERT INTO LIST VALUES('111113');
COMMIT;
/*CODE TO GET THE RESULT*/
SELECT CONCAT('{',GROUP_CONCAT(RESULT),'}') AS RESULT FROM
(
SELECT DISTINCT COLUMN1 AS RESULT FROM
(
Select a.column2 as column1,b.column2
from
(
Select * from
tables
where column1 in (SELECT COLUMN1 FROM LIST)
) a
inner join
tables b
on a.column2=b.column1
UNION ALL
Select b.column2 as column1,b.column1 as Column2
from
(
Select * from
tables a
where column2 in (SELECT COLUMN1 FROM LIST)
) a
inner join
tables b
on a.column1=b.column2
) a
UNION ALL
SELECT DISTINCT COLUMN2 AS RESULT FROM
(
Select a.column2 as column1,b.column2
from
(
Select * from
tables
where column1 in (SELECT COLUMN1 FROM LIST)
) a
inner join
tables b
on a.column2=b.column1
UNION ALL
Select b.column2 as column1,b.column1 as Column2
from
(
Select * from
tables a
where column2 in (SELECT COLUMN1 FROM LIST)
) a
inner join
tables b
on a.column1=b.column2
) a
UNION ALL
SELECT DISTINCT COLUMN2 AS RESULT FROM
(
Select distinct a.Column1, a.column2
from
(
Select * from
tables a
where column2 in (SELECT COLUMN1 FROM LIST)
) a
inner join
(
Select * from
tables a
where column2 in (SELECT COLUMN1 FROM LIST)
) b
on a.column1=b.column1
where a.column2 not in
(
Select column1 from
(
Select b.column2 as column1,b.column1 as Column2
from
(
Select * from
tables a
where column2 in (SELECT COLUMN1 FROM LIST)
) a
inner join
tables b
on a.column1=b.column2
) a
)
) a
) a;
Hope this helps:-)

How to auto adjust ID value (primary key) in oracle?

Right now I have created a sequence and a trigger to auto increment the ID value like this:
CREATE OR REPLACE TRIGGER "RTH"."TBL_USER_TRIGGER"
BEFORE INSERT ON TBL_USER
FOR EACH ROW
BEGIN
SELECT TBL_USER_SEQ.nextval
INTO :new.USR_ID
FROM dual;
END;
ALTER TRIGGER "RTH"."TBL_USER_TRIGGER" ENABLE;
Let say I have three rows:
User ID FIRSTNAME LASTNAME
====================================
1 John smith
2 James smith
3 Pat smith
When I delete the first row(1) I want the ID values to auto correct itself to correct numbers so that second row ID values becomes 1 and third row ID values becomes 2
Is it possible in oracle? or do I have do it through code as I am using Java to insert records into table when user submits a form.
Java DAO class:
public class RegistrationDAO {
public void insert(User user) {
try {
Connection con = DBConnection.getConnection();
String query = "insert into TBL_USER(USR_FIRST_NAME,USR_LST_NAME,USR_PRIMARY_EMAIL,USR_PASSWORD) values(?,?,?,?)";
PreparedStatement pst = con.prepareStatement(query);
pst.setString(1, user.getFirstName());
pst.setString(2, user.getLastName());
pst.setString(3, user.getEmail());
pst.setString(4, user.getPassword());
pst.executeUpdate();
} catch (Exception e) {
System.out.println("####Record insertion error in Registration DAO####");
System.out.println(e);
}
}
}
The simple answer is: "No, you don't want to do that." The purpose of an id is to uniquely identify each row. A sequential id also has the feature that it provides insertion order. It is not intended to change over time. Row 1 is Row 1 is Row 1.
If you want ordering, then declare the id to be the primary key and use a query such as this:
select t.*, row_number() over (order by usr_id) as seqnum
from t;
Ideally, you should not be changing USER ID values. But still if there is requirement. Then below are the steps.
Create a procedure to reset the sequence TBL_USER_SEQ. This is needed as you are resetting the USER ID values. So after resetting, whenever you insert new record, Sequence should start with proper value ( i.e. MAX USER_ID value of the table). So that there will be no gap in USER_ID
Write Delete Trigger on table which will adjust USER_ID values.
Procedure to reset sequence
CREATE OR REPLACE PROCEDURE reset_sequence_p (p_seq IN VARCHAR2, p_new_seq NUMBER)
AS
l_value NUMBER;
BEGIN
-- Select the next value of the sequence
EXECUTE IMMEDIATE 'SELECT ' || p_seq || '.NEXTVAL FROM DUAL' INTO l_value;
-- Alter the sequnce to increment by the difference
EXECUTE IMMEDIATE 'ALTER SEQUENCE ' || p_seq || ' INCREMENT BY ' || ( p_new_seq - l_value ) ;
-- Increment to next value after diference
EXECUTE IMMEDIATE 'SELECT ' || p_seq || '.NEXTVAL FROM DUAL' INTO l_value;
-- Set the increment back to 1
EXECUTE IMMEDIATE 'ALTER SEQUENCE ' || p_seq || ' INCREMENT BY ' || 1 ;
END reset_sequence_p;
Delete Trigger
CREATE OR REPLACE TRIGGER "RTH"."TBL_USER_TRIG_DEL"
BEFORE DELETE
ON TBL_USER
FOR EACH ROW
DECLARE
v_new_user_id_seq NUMBER;
PRAGMA AUTONOMOUS_TRANSACTION;
BEGIN
-- Update USER_ID value for all remaining records greater than USER_ID that got deleted.
UPDATE TBL_USER
SET USER_ID = USER_ID - 1
WHERE USER_ID > :old.USER_ID;
-- Retrieve max USER_ID available in table.
SELECT MAX (user_id) INTO v_new_user_id_seq FROM TBL_USER;
-- Call procedure to reset sequence
reset_sequence_p ('TBL_USER_SEQ', v_new_user_id_seq);
COMMIT;
END;
NOTE : Make sure that Primary key on table is disabled before execution of Delete statement.
I hope this helps.

MySql database table having Xml String. How to Import that data into another mysql Table

I have one Person named table's. this table's column "outsourcedData" contain below xml as an String :
<person>
<educations total="2">
<education>
<school-name>Delhi University</school-name>
<degree>Master of Science (MSc)</degree>
<field-of-study>Banking and Financial Support Services</field-of-study>
<start-date>
<year>2009</year>
</start-date>
<end-date>
<year>2013</year>
</end-date>
</education>
<education>
<school-name>American University</school-name>
<degree>Bachelor of Arts (BA)</degree>
<field-of-study>Business Administration and Management, General</field-of-study>
</education>
</educations>
</person>
There are lots of similar rows available into this table. Is there is any way so I can load these data parse and insert into education table.
There are lots of row I am having in my database. But now I want to import this data into new table Education which I newly created in database corresponding fields with xml.(SchoolName,degree......).
In Mysql Database what is the best way to migrate this database.
I am stuck in this place. Please help. help
create table person (id int,outersource varchar(1024));
insert into person values(1,'<?xml version="1.0" encoding="UTF-8" standalone="yes"?><person><educations total="2"><education><school-name>Delhi University</school-name><degree>Master of Science (MSc)</degree><field-of-study>Banking and Financial Support Services</field-of-study><start-date><year>2009</year></start-date><end-date><year>2013</year></end-date></education><education><school-name>American University</school-name><degree>Bachelor of Arts (BA)</degree><field-of-study>Business Administration and Management, General</field-of-study></education></educations></person>');
create table education( schoolName varchar(255), degree varchar(255),start_year datetime, end_year datetime);
Any Store Procedure we can do this ?
Originally problem was that. I have three tables. first table where xml string data exist and two new table for this xml string parsing. Parent table contain school name + userid unique combinate. during parsing xml if any node contain same school name + user id than data saved into child table.
this child table having referece of this parent table. use below stored procedure.
CREATE DEFINER=`teneqs`#`localhost` PROCEDURE `xxx`()
begin
declare v_row_index int unsigned default 0;
declare v_row_count int unsigned;
declare v_xpath_row varchar(255);
declare userId int;
declare userEduInfoId int;
declare p_xml text;
declare p_xpath_row varchar(255) default '//educations[1]/education';
declare done int;
DECLARE outsourcedUserDataCursor CURSOR FOR select user_id, data from source_table where sourceType='LINKED_IN' order by user_id;
OPEN outsourcedUserDataCursor;
outsourcedUserDataCursor_loop:
LOOP FETCH outsourcedUserDataCursor INTO userId,p_xml;
Set v_row_index := 0;
-- SET done := 0;
select userId,p_xml;
-- calculate the number of row elements.
set v_row_count := extractValue(
p_xml
, concat(
'count('
, p_xpath_row
, ')'
)
);
select v_row_count as "Education Count" ;
IF v_row_count > 0 THEN
-- loop through all the row elements
while v_row_index < v_row_count do
set v_row_index := v_row_index + 1;
set v_xpath_row := concat(
p_xpath_row
, '['
, v_row_index
, ']'
);
select v_row_index, v_xpath_row;
begin
DECLARE userEduInfoCursor CURSOR FOR select id from parent where user_id= userId and school_name=extractValue(p_xml,concat(v_xpath_row,'/school-name[1]')) limit 1;
-- DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = 1;
select "Exist into Edu Info table: ",userId,extractValue(p_xml,concat(v_xpath_row,'/school-name[1]')) as 'SchoolName';
OPEN userEduInfoCursor;
-- IF done = 1 THEN
-- select done "Done";
-- END IF;
select 'userEduInfoCursor will be open';
LOOP
FETCH userEduInfoCursor INTO userEduInfoId;
select userEduInfoId;
IF userEduInfoId is NOT NULL then
select "in side if, userid is not null";
-- Insert UserEducationInfo
insert into child(
a
,b
,c
,d
,e
,f
,g
,h
,i
,j
) values(
userID
,userEduInfoId
,extractValue(p_xml,concat(v_xpath_row,'/school-name[1]'))
,'degree'
,'fieldOfStudy'
,'January'
,'2001'
,'December'
,'2014'
,'description');
ELSE
select "in side else";
close userEduInfoCursor;
-- User Info Inserted.
insert into parent (
school_name
,user_id,
creationDate,
lastmodified)
values (
extractValue(p_xml,concat(v_xpath_row,'/school-name[1]'))
,userId
,now()
,now()
);
OPEN userEduInfoCursor;
FETCH userEduInfoCursor INTO userEduInfoId;
-- Detaild Information Entered
insert into child(
a
,b
,c
,d
,e
,f
,g
,h
,i
,j
) values(
userID
,userEduInfoId
,extractValue(p_xml,concat(v_xpath_row,'/school-name[1]'))
,'degree'
,'fieldOfStudy'
,'January'
,'2001'
,'December'
,'2014'
,'description');
END IF;
END Loop;
close userEduInfoCursor;
end;
-- check userid & school name already exist into info table -> insert into details table.
end while;
END IF;
end LOOP outsourcedUserDataCursor_loop;
close outsourcedUserDataCursor;
end
I tired with this store procedure but there one issue with this. Only one single record insert into Parent table remaing other records inserted into another child table.
Please correct me where i did mistake.

Categories

Resources