Is it possible to insert data into table using two select statements in one query? - sql

I am working with databases in which I have 3 tables one is skill table the other one is experience and the third one is Experience_skill table in this table I have foreign keys now the question is both foreign keys are primary keys as well. Let say I am storing data into skill table as well as in experience table how can I insert the the both keys data there in Experience_skill table. I have tried following queries.
insert into Experience_skill(eid, Skill_Id)
select eid
from Experience
where eid=2
union
select Skill_Id
from Skills
where Skill_Id=2
error I get:
The select list for the INSERT statement contains fewer items than the insert list. The number of SELECT values must match the number of INSERT columns.
Than i tried this one.
insert into Experience_skill(eid)select eid from Experience where eid=2
it gives me this error:
Cannot insert the value NULL into column 'Skill_Id', table 'resume.dbo.Experience_skill'; column does not allow nulls. INSERT fails.
Please help me out
here are the snapshots of the table first snap shot is of skill table
the second one is experience table
And this one is EXperience_skill table where i have my foreign keys

When using INSERT INTO, you need to supply ALL of the columns in the destination table (that do not allow NULLs) in each ROW of the SELECT.

Related

SQL Server : Insert into Multiple Tables with Foreign Keys

I'm working on a project tracking grocery expenses. I have the following tables with predefined values already inserted:
Store (where we bought the food)
Shopper (me or my wife)
Category (of food)
I also have tables that are awaiting input.
They are:
Receipt (one shopping trip with multiple food items)
Food (each food item)
FoodReceipt (bridge table between Receipt and Food)
I have my constraints set up the way I need them, but I am at a bit of a loss when it comes to writing an INSERT statement that would allow me to insert a new record that references values in the other tables. Any thoughts would be greatly appreciated.
Thanks!
SCOPE_IDENTITY will give you the single value of the last identity. While it may well work in this case, that isn't necessarily the best approach in the general case when you want to insert in sets.
I'd consider using the OUTPUT clause to output the inserted items ID into a temp table, then you can join them back to the subsequent inserts.
`INSERT INTO... OUTPUT INSERTED.ID INTO tempIDs
INSERT INTO other_table inner join tempIDs ...`
Wrap it up in a SP.
https://learn.microsoft.com/en-us/sql/t-sql/queries/output-clause-transact-sql?view=sql-server-2017
Using the final three tables as an example, insert into the reciept table and use the ScopeIdentity() function to get the id (you have to use an identity column as the primary key). Repeat the following for each food item - insert into the food table, use ScopeIdentity to get the primary key and then insert a row into FoodReceipt the saved value for the receipt and the saved value for the current food row.

Assign unique ID to duplicates in Access

I had a very big excel spreadsheet that I moved into Access to try to deal with it easier. I'm very much a novice. I'm trying to use SQL via Access.
I need to assign a unique identifier to duplicates. I've seen people use DENSE_RANK in SQL but I can't get it to work in Access.
Here's what I'm trying to do: I have a large amount of patient and sample data (20k rows). My columns are called FULL_NAME, SAMPLE_NUM, and DATE_REC. Some patients have come in more than once and have multiple samples. I want to give each patient a unique ID that I want to call PATIENT_ID.
I can't figure out how to do this, aside from typing it out on each row. I would greatly appreciate help as I really don't know what I'm doing and there is no one at my work who can help.
To illustrate the previous answers' textual explanation, consider the following SQL action queries which can be run in an Access query window one by one or as VBA string queries with DAO's CurrentDb.Execute or DoCmd.RunSQL. The ALTER statements can be done in MSAcecss.exe.
Create a Patients table (make-table query)
SELECT DISTINCT s.FULL_NAME INTO myPatientsTable
FROM mySamplesTable s
WHERE s.FULL_NAME IS NOT NULL;
Add an autonumber field to new Patients table as a Primary Key
ALTER TABLE myPatientsTable ADD COLUMN PATIENT_ID AUTOINCREMENT NOT NULL PRIMARY KEY;
Add a blank Patient_ID column to Samples table
ALTER TABLE mySamplesTable ADD COLUMN PATIENT_ID INTEGER;
Update Patient_ID Column in Samples table using FULL_NAME field
UPDATE mySamplesTable s
INNER JOIN myPatientsTable p
ON s.[FULL_NAME] = p.[FULL_NAME]
SET s.PATIENT_ID = p.PATIENT_ID;
Maintain third-norm principles of relational databases and remove FULL_NAME field from Samples table
ALTER TABLE mySamplesTable DROP COLUMN FULL_NAME;
Then in a separate query, add a foreign key constraint on PATIENT_ID
ALTER TABLE mySamplesTable
ADD CONSTRAINT PatientRelationship
FOREIGN KEY (PATIENT_ID)
REFERENCES myPatientsTable (PATIENT_ID);
Sounds like FULL_NAME is currently the unique identifier. However, names make very poor unique identifiers and name parts should be in separate fields. Are you sure you don't have multiple patients with same name, e.g. John Smith?
You need a PatientInfo table and then the SampleData table. Do a query that pulls DISTINCT patient info (apparently this is only one field - FULL_NAME) and create a table that generates unique ID with autonumber field. Then build a query that joins tables on the two FULL_Name fields and updates a new field in SampleData called PatientID. Delete the FULL_Name field from SampleData.
The command to number rows in your table is [1]
ALTER TABLE MyTable ADD COLUMN ID AUTOINCREMENT;
Anyway as June7 pointed out it might not be a good idea to combine records just based on patient name as there might be duplicates. Better way will be treat each record as unique patient for now and have a way to fix patient ID when patient comes back. I would suggest to go this way:
create two new columns in your samples table
ID with autoincrement as per query above
patientID where you will copy values from ID column - for now they will be same. But in future they will diverge
copy columns patientID and patientName into separate table patients
now you can delete patientName column from samples table
add column imported to patients table to indicate, that there might be some other records that belong to this patient.
when patients come back you open his record, update all other info like address, phone, ... and look for all possible samples record that belong to him. If so, then fix patient id in those records.
Now you can switch imported indicator because this patient data are up to date.
After fixing patientID for samples records. You will end up with patients with no record in samples table. So you can go and delete them.
Unless you already have a natural key you will be corrupting this data when you run the distinct query and build a key from it. From your posting I would guess a natural key would be SAMPLE_NUM. Another problem is that if you roll up by last name you will almost certainly be combining different patients into one.

SQL inserting rows from multiple tables

I have got an assignment. We have been given a table, MAIN_TABLE, which has a column patient_id as foreign key.
I need to make a separate table named patient which has patient_id as a primary key along with some other attributes such as name and address.
I did successfully create schema of this table. Now there is a serious problem I am facing. After creating this table I used insert statement to insert values for name and address from a dummy table.
Till this point everything works fine. However, the column patient_id is still empty rather I have set it to 0 by default.
Now the problem is that I need to get values into this column, patient_id, from the patient_id column of MAIN TABLE.
I can't figure out how do I do this? I did try to use:
UPDATE patient
SET patient_id=(select id from MAIN_TABLE)
BUT this gives me error that multiple rows returned which does make sense but what condition do I put in where clause then?
That sounds strange. How can there be a table MAIN_TABLE with a foreign key patient_id but the master table patient does not exist. Where do that patient_ids in MAIN_TABLE come from?
I suggest not to insert your data from a dummy table alone and then try to update it. But insert it with both - the MAIN_TABLE and the dummy table joined. If you can not join them. You would also not be able during the update.
So since i think they have no connected primary/foreign keys the only way to join them is using a good business key. Do you have a good business key?
You are talking about persons. So First Name, Last Name, Birth Day, Address often is good enough. But you have to think about it.
With your given data I can only give you some kind of meta insert statement. But you will get the point.
Example:
insert into patient (col1, col2, col3)
select
a.colA,
a.colF,
b.colX
from
dummy_table a
inner join MAIN_TABLE b on a.colN=b.colA and a.colM=b.colB
And: If patient_id is your primary key in patient you should ensure that it is even not possible to have duplicate values or null in this column. And you should use constraints to ensure your data integrity.
http://docs.oracle.com/cd/B19306_01/server.102/b14200/clauses002.htm

Oracle INSERT multiple rows

My statement will insert two out of the four student IDs. The ones that are inserted are Id's that already exist with another section number. I cant figure out why the other two are not inserted.
INSERT INTO enrollment
(student_id,section_id,enroll_date,created_by,created_date,modified_by,modified_date)
SELECT
student_id,'48',SYSDATE,'KABEL',SYSDATE,'KABEL',SYSDATE
FROM enrollment
WHERE student_id IN ('375','137','266','382');
There is nothing much wrong in your query. You are typo or by mistake choose INSERT table and SELECT query from one table as this does not make any sense, to select from one table and insert into same table.
Your select and Insert statement using the same table enrollment.
These should be two different table.
INSERT INTO enrollment <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<-------Here Problem
(student_id,section_id,enroll_date,created_by,created_date,
modified_by,modified_date)
SELECT
student_id,'48',SYSDATE,'KABEL',SYSDATE,'KABEL',SYSDATE
FROM enrollment <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<-------Here Problem
WHERE student_id IN ('375','137','266','382');

What SQL query do I need in order to add lots of empty rows to a table at once?

I understand that what I am asking for may not make a lot of sense, but I none the less have a particular need for it. I have a table that has 500 rows in it. I have another table that has 500 more rows, that I need to merge into the first table. The easiest way I know how to do that is to add 500 rows to the first table, and then use an update statement because then I have a primary key to use to pair the first and second tables.
So how can I add 500 blank rows to my first table? I've been trying to think of a query that would do that, but haven't been able to come up with anything...
You can insert to one table from another table:
INSERT INTO suppliers (supplier_id, supplier_name)
SELECT account_no, name
FROM customers
WHERE city = 'Newark';
You can use insert into statement:
SQlite: select into?
As long as the tables contain the same data structure, you can use a simple query to insert them into your table:
INSERT INTO tableOne SELECT * FROM tableTwo
If you have to manually map the fields, you'll have to change it to the field level insert, such as:
INSERT INTO tableOne(columnOne,columnTwo) SELECT column3, column4 FROM tableTwo
You can add the standard WHERE statements to these as well.
Hope that helps.