Insert data from excel sheet into linked access tables - sql

I have multiple(About 9) access tables with One to Many and Many to one relationships(All tables are linked someway, There is a master table with has one to many and many to one relationship with all the tables). I want to insert data into three tables from an excel sheet.
Excel sheet provided has data for only three of the linked tables. How can I best approach this? How complicated insert query I am looking at here?
Any suggestions much much appreciated.
EDIT:
Here is my table structure:
Subject
SubjectID (Autonumber) Primary Key
MasterID (Number) Foreign Key
Description (Text)
Master
MasterID (Autonumber) Primary Key
StatusID (Number) Foreign Key
StudentID (Text)
Description (Text)
Status
StatusID (Autonumber) Primary Key
Description (Text)
Table Relationships:
Master (One) --> (Many) Subject
Status (One) --> (Many) Master
Data from Excel:
StudentID Subject Status
JP121 Math Active
SP223 Bio Active
JK111 Chem In Suspense
LS433 Bio In Active
NP833 Math In Active
SS777 Chem Active
BK299 Bio In Suspense

Depending on yout table structure, this the process i would recommend
1.) Build Status table by selecting all Unique STATUS from Excel.
2.) Build the Subject Table by selecting all Unique Subjects from Excel.
3.) Once these tables are populated, you can proceed to build your master table. For every student row in the excel, fetch the statusID from status table and subjectID from subject table
Does this make sense?
Regarding Status table My understanding is that you intend to populate Status ID something like this
StatusID | Description
---------|------------
1 | Active
2 | InActive
3 | In Suspense
also to add, Subject table does not require MasterID column. Instead you can have SubjectID column in Master table

Related

Validate whether value in one table is the same as in related table - performance

Let's say I have two tables and I'm doing all the operations in .NET Core 2 Web API.
Table A:
Id,
SomeValue,
TeamName
Table B:
Id,
Fk_Id_a (references Id in table A),
OtherValue,
TeamName
I can add and get records from table B indepedently.
But for every record in Table B TeamName has to be the same as for it's corresponidng Fk_Id_a in Table A.
Assume these values comes in:
{
"Fk_Id_a": 3,
"SomeValue": "test val",
"TeamName": "Super team"
}
Which way would be better to check it in terms of performance? 1ST way requires two connections, when 2nd requires storing some extra keys etc.
1ST WAY:
get record from Table A for Fk_Id_a (3),
check if TeamName is the same as in coming request (Super team),
do the rest of the logic
2ND WAY:
using compound foreign keys and indexes:
TableA has alternate unique key (Id, TeamName)
TableB has foreign compound key (Fk_Id_a, TeamName) that references TableA (Id, TeamName)
SQL SCRIPT TO SHOW:
ALTER TABLE Observation
ADD UNIQUE (Id, PowelTeamId)
GO
ALTER TABLE ObservationPicturesId
ADD FOREIGN KEY(ObservationId, PowelTeamId)
REFERENCES Observation(Id, PowelTeamId)
ON DELETE CASCADE
ON UPDATE CASCADE
EDIT: Simple example how the tables might look like. TeamName has to be valid for FK referenced value in Table A.
Table A
ID | ObservationTitle | TeamName
---------------------------------------
1 | Fire damage | CX_team
2 | Water damage | CX_team
3 | Wind damage | Dd_WP3
Table B
ID | PictureId | AddedBy | TeamName | TableA_ID_FK
-----------------------------------------------------
1 | Fire | James | CX_team | 1
2 | Water | Andrew | CX_team | 1
3 | Wind | John | Dd_WP3 | 3
Performance wise, the 2nd option would be faster because there is no comparison to check (the foreign key will force that they match when inserting, updating or deleting) when selecting the rows from the table. It would also make a unique index on table A.
That being said, there is something very fishy about the structure you mention. First of all why is the TeamName repeated in table B? If a row in table B is "valid" only when the TeamName match, then you should enforce that no row should be inserted with a different TeamName, throught the ID foreign key (and not actually storing the TeamName value). If there are records on table B that represent another thing rather than the entity that is linked to table A then you should split it onto another table or just update the foreign key column when the team matches and not always.
The issue is that you are using a foreign key as a partial link, making the relationship valid only when an additional condition is true.

How to associate two tables based on a unique id

I have two tables I want to join in SQL Server.
One houses call data and has a unique id Login_ID. This table does not contain the employees name.
The other table does not have a unique id for employees.
What I need to do is join these two tables so I can see call data and ticket data simultaneously by employee.
Unfortunately, there is no correlating column for Login_ID in the ticket table to link employee data.
Example of call data table:
Login_ID | Calls | CallTime | Date |
00000001 | 34 | 349874 | 030317 |
Example of ticket table:
Name | Ticket_Num | Date |
Some Emp | 5456465434 | 030317 |
So what happens is: anytime someone changes their name, they basically have a new ID in this table. It's awful.
I only need the data from around 18 employees.
My question is: how can I associate the Login_ID with the ticket table?
Hopefully I made this clear enough!
You should to store the association using what is known as a Foreign Key. This will ensure the integrity of the relationships between your data and can help optimize your queries when you are trying to pull associated data from different tables.
A FOREIGN KEY is a key used to link two tables together.
A FOREIGN KEY is a field (or collection of fields) in one table that
refers to the PRIMARY KEY in another table.
The table containing the foreign key is called the child table, and
the table containing the candidate key is called the referenced or
parent table.
You get query associated date using a join.
If you have a 1:1 relationship you add Login_ID as a field to your ticket table and you can join your table on Login.Login_ID = Tickets.Login_Id.
Alter Table Tickets
Add Login_ID int not null Constraint "FK_Tickets_LoginId" References Tickets(Login_Id)
// USAGE:
Select * from Logins Join Tickets on Logins.Login_ID=Tickets.Login_Id where Login_ID=#LoginId
If you can't modify either table then you can create a new table, perhaps Logins2Tickets which will contain two fields Login_ID and Ticket_Num
You can then join your Logins to Logins2Tickets on Login.Login_ID = Tickets.Login_Id and join Logins2Tickets to Tickets on Logins2Tickets.Ticket_Num = Tickets.Ticket_Num
Create Table Logins2Tickets
(
Login_ID int not null constraint "FK_Logins2Tickets_Login_ID" References Logins(Login_Id)
Ticket_Num bigint not null constraint "FK_Logins2Tickets_Ticket_Num" References Tickets(_Login_ID)
)
// USAGE:
Select *
From
Logins l Join Logins2Tickets lt
on l.Login_ID=lt.Login_ID
Join Tickets t
on lt.Ticket_Num=t.Ticket_Num
WHERE Login_ID=#LoginId

Existing table design change in SQL Server

My existing table structure is below:
Students table and columns are below:
Year
Student_Id
Subject_Type_Id
Quarter
Complete_DTTM
Column1
Existing data like below:
Students:
Year Student_Id Quarter Subject_Type_Id Complete_DTTM Column1
---------------------------------------------------------------------------------------
2006 1 1 1 Null x
2006 1 2 1 10/2/2006 xyz
2006 1 2 2 10/30/2006 abc
2006 1 2 3 11/20/2006 def
One student can take multiple subjects by saving each subject separately by picking from DropDownList.
Now new requirement is one student can take multiple subjects by selecting from Checkboxes and provide data for Column1 and Complete_DTTM and save.
The difference between old and new requirement is how user selecting subject types, in old from Drop down list, able to pick one subject only, Column1 and Complete_DTTM are different for each subject.
With the new requirement, they can pick multiple subjects from check boxes for a student and column1 and Complete_DTTM is same for all subjects.
NEW data going to be like below:
Year Student_Id Quarter Subject_Type_Id Complete_DTTM Column1
--------------------------------------------------------------------------
2015 1 1 1, 2, 3, 4 12/31/2015 abcdef
2015 1 2 1, 2, 3, 4, 5 1/1/2016 xyz
How do I change ‘Students’ table (I can add new table) to support multiple subject Ids and also needs to support old data (shown above for year 2006)?
Thanks in advance
You need to make a table that will house just the student data. Then you will need to make a table that will house Subject Type data. The a table to link them together.
CREATE TABLE Student (ID INT NOT NULL PRIMARY KEY, NAME VARCHAR(50) NOT NULL,n...)
Create Table for subject
CREATE TABLE Subject (ID INT NOT NULL PRIMARY KEY, Subject_Name VARCHAR(50)NOT NULL,n...)
Then You will need a table to link these two together.
CREATE TABLE Student_Suject_Link (Student_ID INT NOT NULL, SUBJECT_ID INT NOT NULL)
The link table will need to have a foreign key realtionship to the Student table and the Subject table. Student_ID needs to be a foreign key to the ID column in the student table and same for the subject table. The SUbject_ID needs to be a foreign key to the ID in the Subject table. This should satisfy 3rd normal form. And if you need to grab data it is easy enough to join tables to get what you need. I relaize it seems to create more work but it is infinately easier to manage that adding lists to tables. You can of course add other fields you deem necessary into the table it is just necessary to have the ID's to relate on. Hope this helps.
You now have a one to many relationship and you need a child table for the many part of the relationship. Do not ever store data in a comma delimited list. This is a way to totally break your performance when you want to find data int hose tables. It is just bad deign. You need to normalize those tables and I am sure that this is why you have been given this particular exercise.

Can a table title be a Primary Key?

I'm trying to retrofit some tables to an existing database. The existing database has equipment numbers and I'm trying to add in tables with more information on that equipment. Ideally, I'd like to make the table titles the ID numbers and set those as the PK of that table, making the ID numbers in the equipment list the FK.
Is it possible to set the table title as the PK? Here's an example of one of the tables, and I'd like to make "E0111" the PK.
CREATE TABLE E0111(
EQUIPMENT Varchar(200),
MAINTENANCE varchar(200),
CYCLE varchar(200)
);
No you can't do this because the primary key needs to be unique for every row of your table. If you "could" use the table name as the primary key it would be the same for every row.
You should use a unique column in your table as the primary key.
Also, I have no idea how you could achieve this with SQLite or any DBMS.
First thing before I even get anywhere near answering the question about the table names being primary keys, we need to take a step back.
You should NOT have a table for each piece of equipment.
You need an Equipment table, that will store all of your pieces of Equipment together. I assume you have that already in the existing database.
Hopefully it is keyed with a Unique Identifier AND an Equipment Number. The reason for having a separate Unique Identifier, is that your database server uses this for referential integrity and performance - this is not a value that you should show or use anywhere other than inside the database and between your database and whatever application you are using to modify the database. It should not typically be shown to the user.
The Equipment Number is the one you are familiar with (ie 'E0111'), because this is shown to the User and marked on reports etc. The two have different purposes and needs, so should not be combined into a single value.
I will take a stab at what your Equipment table may look like:
EquipmentId int -- database Id - used for primary key
EquipmentName Varchar(200) -- human readable
EquipmentDescription Text
PurchaseDate DateTime
SerialNumber VarChar(50)
Model Varchar(200)
etc..
To then add the Maintenance Cycle table as you propose above it would look like:
MaintenanceId int -- database Id - used for primary key this time for the maintenance table.
EquipmentId int -- foreign key - references the equipment table
MaintenanceType Varchar(200)
DatePerformed DateTime
MaintenanceResults VarChar(200)
NextMaintenanceDate DateTime
To get the results about the Maintenance Cycle for all equipment, you then JOIN the tables on the 2 EquipmentIds, ie
SELECT EquipmentName, EquipmentDescription, SerialNumber, MaintenanceType DatePerformed
FROM Equipment
JOIN MaintenanceCycle ON Equipment.EquipmentId = Maintenance.EquipmentId
WHERE EquipmentName = 'E0111'
You cannot make the name of the table a primary key.
All primary keys should be unique and a table column not table name. This is the general rule of thumb for a priamry key. There are plenty of resources on the internet about Primary keys.
Here are just afew:
http://www.w3schools.com/sql/sql_primarykey.asp
http://database-programmer.blogspot.co.uk/2008/01/database-skills-sane-approach-to.html
The name of a table should be descriptive of what is hold within it. See that data table as a drawer where you shall label what it contains.
In my humble point of view, the ID of an equipement shall only be labeled as-is on the equipement in question. Otherwise, in your database, it shall be the table Equipments that prevails with the ID of each piece of equipment you have.
Then, if you have other equipment-related information to save, add another table with the kind of information it shall contains, with the ID of the related equipment for which this information is saved.
For example, let's say we hold a maintenance schedule over your equipment.
Equipments
-----------------------------------------------------
Id | Description | Location | Brand | Model
-----------------------------------------------------
1 | Printer/Copier| 1st Floor | HP | PSC1000
Maintenances
---------------------------------------------------------
Id | Description | Date | EquipmentId | EmployeeId
---------------------------------------------------------
Note that the EmployeeId column shall be there only if one requires to know who did what maintenance and when, for instance.
MaintenanceCycles
--------------------------------------------
Id | Code | Description | EquipementId
--------------------------------------------
1 | M | Monthly | 1
This way, every equipment can have its cycle, and even multiple cycles per equipment if required. This lets you the flexibility that you need for further changes.

When adding data to a table, it doesn't show up in the Foreign key of the other table

I have a table COURSE which has two attributes COURSECODE (PK) and COURSENAME
I also have another table COURSEUNIT, which has three attributes COURSECODE (PK) (FK) UNITCODE (PK) (FK) and CREDIT .
When I add data to the table COURSE it doesn't add the data to the COURSEUNIT table. What is the problem?
Foreign key does not mean that you get one row for each key in the referenced table. It only means that any row in the COURSEUNIT table must reference an existing row in COURSE.
Those are 2 different tables and you have to manage the relation, you have to insert the data first in the course table then take the id that will be generated from this insert and make another insert in the coursecode table, they will not be inserted automatically.
No problem there, that's how SQL works, you'll need a second INSERT statement to populate the COURSEUNIT table.
You need to write the query to populate the second table, how else will it know what values besides the FK to put in it? Child tables do not auto populate in any database.