Store list of words to sql - sql

I have a sqlite database with id, name and reason
I have a text file that contains a list in this format:
Name1
Name2
How can I store each name in a different row? so name will be filled in and reason will be empty

Use INSERT to add individual records into a table:
INSERT INTO table ( id, name ) VALUES ( <id>, <name> );
where I use <id>, <name> as placeholders for actual values ( <name> is the data from the file, <id> you have to supply unless id is an autoincrement column ). You need 1 statement for each line in the file.
How you create these statements is up to you:
By hand
In your favorite text editor that has a column mode
Write code and use a library that can interface with a text file as a database.
Use sepcialized tools
In the case of 3.) you would rewrite your insert statement along
INSERT INTO table ( id, name ) SELECT ... FROM <pseudo-db>
Consult the docs of the respective library on how to build the specific statement.

INSERT INTO Students(Id, Name, Reason) VALUES(1, 'Ahmad','');
INSERT INTO Students VALUES(2, 'Aly','');
SELECT * FROM Students;
Hence,it will show a list of name in row with reason column empty.

Related

Can I use return value of INSERT…RETURNING in a SELECT query?

I am trying to extract the name which is generated from an trigger function in postgres.
It generated after insert meaning when I do
INSERT INTO table VALUES(....) RETURNING id,name
I only get the id and not the name, since the trigger only have generate the id, and not the name in the insert statement.
The name is generated by a trigger AFTER INSERT.
I can though extract the name using a select statement as such
SELECT name from registration_table where id = ANY(id)
how do nest these two queries together?
how do I pass the id property to the next query?

SQL: Is it possible to insert into two tables at the same time with autogenerated id output from first table into second

My database contains two tables FileStore and FileRepository.
The FileStore table contains 3 columns Id (autogenerated uniqueidentifier), FileName and Description
-> In Initial state with demo data
The FileRepository table contains 3 columns Id (autogenerated uniqueidentifier), Name and FileId (this refers to the Id column in FileStore table) -> In Initial state with demo data
I get an array of FileStore Ids as a search criteria. With the same I need to create a duplicate row in the FileStore table first for each of the criteria satisfied. I need to do the duplicate row creation for the second table FileRepository as well based on the same data on the FileId column. Here but I need to update the newly created row's FileId column with the autogenerated Id column from the FileStore operation.
Say referring to the attached images if I need to duplicate Files File 1(with Id b3304dc4-4f2e-46d4-8f64-a597edb02e96) and File 2(with Id 7cb40baf-1ecf-4e5f-92ff-57029a20e623) this is how the tables should have data after the operation
FileStore db after duplication should have data thus:
FileRepository db after duplication should have data thus:
Which is the best way to do this? Is it possible to achieve this with a query without any loops?
For the first table I can insert and get the inserted Ids thus:
INSERT INTO FileStore(FileName,Description)
OUTPUT INSERTED.Id as InsertedIds
SELECT
FileName, Description
from FileStore
where Id IN ('b3304dc4-4f2e-46d4-8f64-a597edb02e96','7cb40baf-1ecf-4e5f-92ff-57029a20e623')
But was unsure about the query to update the FileRepository table which takes the InsertedIds as input
INSERT INTO FileRepository(Name,FileId)
SELECT
Name, {{How do I use InsertedDetails here?}}
from FileRepository
where FileId IN ('b3304dc4-4f2e-46d4-8f64-a597edb02e96','7cb40baf-1ecf-4e5f-92ff-57029a20e623')
PS: This is just a reference table I created for this question. Please let me know in case I need to make it more clear
As I mention, you need to use the OUTPUT clause. This is pseudo-SQL in the abscence of consumable sample data and expected results. You'll need to remove/change the parts in braces ({}) appropriately:
DECLARE #Output table (ID uniqueindentifier,
{Other Columns});
INSERT INTO FileStore(FileName,Description)
OUTPUT INSERTED.Id, {Other Columns}
INTO #Output
SELECT FileName,
Description
from FileStore
where Id IN ('b3304dc4-4f2e-46d4-8f64-a597edb02e96','7cb40baf-1ecf-4e5f-92ff-57029a20e623');
INSERT INTO FileRepository(Name,FileId)
SELECT FR.Name,
O.ID
from FileRepository FR
{CROSS} JOIN #Output O {ON Some Condition}
where FileId IN ('b3304dc4-4f2e-46d4-8f64-a597edb02e96','7cb40baf-1ecf-4e5f-92ff-57029a20e623')
At first, insert your parent table's data.
Then
INSERT INTO FileRepository (`id`, `Name`,`FileId`)
VALUES('id_or_auto_generated','name value', SELECT SCOPE_IDENTITY())
SELECT SCOPE_IDENTITY(); will return the most recently auto-generated id of the SQL server database connection.
For other databases : Follow this post

SQL: Insert multiple row with common columns

I have a table into which i will insert and it has 4 columns.
While inserting 3 columns will be same and the other one column will be different for each and it will be taken from another table.
How could i do that?
For exmaple;
INSERT INTO sendMsg (Type,Name,SenderName,Message) values(4, 'john','Mike','Hi, blabla')
i will insert same message also for Bob, instead of john.
and the names which i will send are contained in Names table.
Thank you.
Use a select statement to build up your insert. Something like this could work (as you didn't provide more details):
INSERT INTO sendMsg (Type,Name,SenderName,Message)
SELECT 4, "name" ,'Mike','Hi, blabla' FROM anothertable
-- WHERE ....
Column names are in ", so don't be confused. It's to ensure difference between string and database object.
Inside optinal WHERE you could do maybe something like
WHERE name in ('Bob', 'John', ...)
or whichever algorithm you need to determine the names.

SQLite auto-increment non-primary key field

Is it possible to have a non-primary key to be auto-incremented with every insertion?
For example, I want to have a log, where every log entry has a primary key (for internal use), and a revision number ( a INT value that I want to be auto-incremented).
As a workaround, this could be done with a sequence, yet I believe that sequences are not supported in SQLite.
You can do select max(id)+1 when you do the insertion.
For example:
INSERT INTO Log (id, rev_no, description)
VALUES ((SELECT MAX(id) + 1 FROM log), 'rev_Id', 'some description')
Note that this will fail on an empty table since there won't be a record with id is 0 but you can either add a first dummy entry or change the sql statement to this:
INSERT INTO Log (id, rev_no, description)
VALUES ((SELECT IFNULL(MAX(id), 0) + 1 FROM Log), 'rev_Id', 'some description')
SQLite creates a unique row id (rowid) automatically. This field is usually left out when you use "select * ...", but you can fetch this id by using "select rowid,* ...". Be aware that according to the SQLite documentation, they discourage the use of autoincrement.
create table myTable ( code text, description text );
insert into myTable values ( 'X', 'some descr.' );
select rowid, * from myTable;
:: Result will be;
1|X|some descr.
If you use this id as a foreign key, you can export rowid - AND import the correct value in order to keep data integrity;
insert into myTable values( rowid, code text, description text ) values
( 1894, 'X', 'some descr.' );
You could use a trigger (http://www.sqlite.org/lang_createtrigger.html) that checks the previous highest value and then increments it, or if you are doing your inserts through in a stored procedure, put that same logic in there.
My answer is very similar to Icarus's so I no need to mention it.
You can use Icarus's solution in a more advanced way if needed. Below is an example of seat availiabilty table for a train reservation system.
insert into Availiability (date,trainid,stationid,coach,seatno)
values (
'11-NOV-2013',
12076,
'SRR',
1,
(select max(seatno)+1
from Availiability
where date='11-NOV-2013'
and trainid=12076
and stationid='SRR'
and coach=1)
);
You can use an AFTER INSERT trigger to emulate a sequence in SQLite (but note that numbers might be reused if rows are deleted). This will make your INSERT INTO statement a lot easier.
In the following example, the revision column will be auto-incremented (unless the INSERT INTO statement explicitly provides a value for it, of course):
CREATE TABLE test (
id INTEGER PRIMARY KEY NOT NULL,
revision INTEGER,
description TEXT NOT NULL
);
CREATE TRIGGER auto_increment_trigger
AFTER INSERT ON test
WHEN new.revision IS NULL
BEGIN
UPDATE test
SET revision = (SELECT IFNULL(MAX(revision), 0) + 1 FROM test)
WHERE id = new.id;
END;
Now you can simply insert a new row like this, and the revision column will be auto-incremented:
INSERT INTO test (description) VALUES ('some description');

Retrieve and insert into type objects in oracle

I have created an object type(address-city,state) in Oracle 10g .Then table cust_contact contains field of type address.Can anyone please provide SQL query to insert and retrieve values from this table including the type?
Selection is easy. Just include the type column in the query projection. Assuming that the ADDRESS column is called contact_address:
select id, contact_name, contact_address
from cust_contact
/
With inserts you need to specify the type in the statement:
insert into cust_contact values
(some_seq.nextval
, 'MR KNOX'
, address(34, 'Main Street', 'Whoville', 'SU')
)
/
You can also use the "." syntax when retrieving columns:
select c.contact_address.city from cust_contact c;
Please note that if cust_contact is a table of objects, then you must use the table alias "c".
for example :
first create type object say as address ,for this synatx or query is used:
create type address_ty as object(Street varchar2(50),City char(10),Zip number(6));
now use this address_ty as datatype in the time of table creation
for example:
create table Example(emp_name varchar2(10),emp_id number(10),address address_ty);
this will create table Example having
Address as address_ty as a datatype..
Now insert into Values In Example Table
Insert Into example Values('Sandeep Kumar',595,address_ty('Snap on sector 126','Noida',201301);
tHANX....