SQLExpress create relationship between two tables - database

I have 2 tables.
dbo.Department
dbo.Employee Records
In employee records, I have a field 2 important fields.
Employee ID (Set as my primary Key)
Department ID
In Department, I only have 3 fields
Department ID (set as my primary key)
Name
Location
I want Department ID to be populated with data from dbo.Department so the only options are a pull down list. (EXAMPLE department 100 - Marketing - Floor 1, department 200 - Human Resources - Floor 2 ETC.) To do this, I attempted to create a new foreign key in dbo.Department
First, I right clicked on the keys folder in dbo.Department and selected 'New Foreign Key'
Then, I clicked on the 3 dots I got when I selected the 'Tables and Columns Specific' field as shown below.
This pops up a dialog box where I can set the Primary Key table and the foreign key table. I set the primary key table as Employee Records and the foreign key table as Department. Under both fields, I have Department ID selected as shown below.
When I hit ok I get the following message
'The columns in table "Employee Records" do not match a primary key or UNIQUE constraint'
Am I setting this up wrong? I'm new to database practices so I'm not sure if I'm even using the right technique to do what I am trying to achieve.

You are close, but have your tables reversed. Create your foreign key on the Employees table, not the Departments table. The primary key table in this case is the Departments table.

Related

Binding multiple tables to Winform

I have a Winform that will display columns from 2 tables.
The form will have a bindingnavigator.
The primary table on the form is a "child" of the second table.
I need the opposite of the usual Customer/Orders linkage
where I want to scroll thru the "orders" and automatically
pull the "customer" info.
There is one common column (ID) between the 2 tables. The ID
column in the "orders" table is not unique but the ID column
in the "customer" table is.
The primary key in the "orders" table is a composite of the ID
column and an order# column which is unique.
I was also unable to create a foreign key relationship when
choosing the ID columns in both tables.
I get this error:
"The columns in table 'orders' do not match an existing
primary key or UNIQUE constraint"
What am I missing?
If you have a composite key (I mean your question is indicating it), then you have to add both columns (ID and order) in your foreign key reference.
When table have composite key, you can see a key symbol next to columns that are part of the primary key.
When you have composite key the order of creating FK is important.
Go to keys section of table and select script of primary key as create script to clipboard (right click on primary key and choose). Paste it in new command window and then create FK with order shown in that script of primary key. (So ID and order columns need to be defined in FK in right order)

How do I create a relationship between two tables where one already has a relationship with another table?

I am trying to create a Many to Many relationship with SQL Server Management studio between two tables called Courses and Students. This relationship uses a junction table called Enrollment. I started by creating a 1:M relationship between Students and Enrollment so that the studentId column in the Enrollment table points to the studentId column in the Student table. That worked fine. My problem is occurring while I create my 1:M relationship between Courses and Enrollment. The courseId column in the Enrollment table needs to point to the courseId column in the Courses table. The relationship dialogue comes up and the columns under the Primary Key Table(Enrollment are automatically populated with courseId and studentId. The Courses table doesn't have a studentId column, so I remove this from the columns under the primary key table. This is where I get the error message 'The columns in table Enrollment do not match an existing primary key or UNIQUE value. This method worked fine for creating the 1:M between Students and Enrollment. Why am I getting this error all of a sudden?
The reason is your Courses table has 2 field in it's primary key.
On solution is you add a new field named semesterId in Enrollment table and use both semesterId and courseId when creating foreign key.
Your Courses primary key includes a SemesterID which isn't in the Enrollment table. I'd suggest the SemesterID should be in the Enrollments table rather than in the Courses table as a Student would be enrolled in a course in a particular Semester.

Handling multi-select list in database design

I'm creating a clinic management system where I need to store Medical History for a patient. The user can select multiple history conditions for a single patient, however, each clinic has its own fixed set of Medical History fields.
For example:
Clinic 1:
DiseaseOne
DiseaseTwo
DiseaseThree
Clinic 2:
DiseaseFour
DiseaseFive
DiseaseSize
For my Patient visit in a specific Clinic , the user should be able to check 1 or more Diseases for the patient's medical history based on the clinic type.
I thought of two ways of storing the Medical History data:
First Option:
Add the fields to the corresponding clinic Patient Visit Record:
PatientClinic1VisitRecord:
PatientClinic1VisitRecordId
VisitDate
MedHist_DiseaseOne
MedHist_DiseaseTwo
MedHist_DisearThree
And fill up each MedHist field with the value "True/False" based on the user input.
Second Option:
Have a single MedicalHistory Table that holds all Clinics Medical History detail as well as another table to hold the Patient's medical history in its corresponding visit.
MedicalHistory
ClinicId
MedicalHistoryFieldId
MedicalHistoryFieldName
MedicalHistoryPatientClinicVisit
VisitId
MedicalHistoryFieldId
MedicalHistoryFieldValue
I'm not sure if these approaches are good practices, is a third approach that could be better to use ?
If you only interested on the diseases the person had, then storing the false / non-existing diseases is quite pointless. Not really knowing all the details doesn't help getting the best solution, but I would probably create something like this:
Person:
PersonID
Name
Address
Clinic:
ClinicID
Name
Address
Disease:
DiseaseID
Name
MedicalHistory:
HistoryID (identity, primary key)
PersonID
ClinicID
VisitDate (either date or datetime2 field depending what you need)
DiseaseID
Details, Notes etc
I created this table because my assumption was that people have most likely only 1 disease on 1 visit, so in case there's sometimes several, more rows can be added, instead of creating separate table for the visit, which makes queries most complex.
If you need to track also situation where a disease was checked but result was negative, then new status field is needed for the history table.
If you need to limit which diseases can be entered by which clinic, you'll need separate table for that too.
Create a set of relational tables to get a robust and flexible system, enabling the clinics to add an arbitrary number of diseases, patients, and visits. Also, constructing queries for various group-by criteria will become easier for you.
Build a set of 4 tables plus a Many-to-Many (M2M) "linking" table as given below. The first 3 tables will be less-frequently updated tables. On each visit of a patient to a clinic, add 1 row to the [Visits] table, containing the full detail of the visit EXCEPT disease information. Add 1 row to the M2M [MedicalHistory] table for EACH disease for which the patient will be consulting on that visit.
On a side note - consider using Table-Valued Parameters for passing a number of rows (1 row per disease being consulted) from your front-end program to the SQL Server stored procedure.
Table [Clinics]
ClinicId Primary Key
ClinicName
-more columns -
Table [Diseases]
DiseaseId Primary Key
ClinicId Foreign Key into the [Clinics] table
DiseaseName
- more columns -
Table [Patients]
PatientId Primary Key
ClinicId Foreign Key into the [Clinics] table
PatientName
-more columns -
Table [Visits]
VisitId Primary Key
VisitDate
DoctorId Foreign Key into another table called [Doctor]
BillingAmount
- more columns -
And finally the M2M table: [MedicalHistory]. (Important - All the FK fields should be combined together to form the PK of this table.)
ClinicId Foreign Key into the [Clinics] table
DiseaseId Foreign Key into the [Diseases] table
PatientId Foreign Key into the [Patients] table
VisitId Foreign Key into the [Visits] table

Relational database one to many relation

I am using Access to create a database. I have two tables with the following data.
Car
CarID - PK
CarName
CarPrice
CustomerID
Customers
CustomerID -PK
Username
Password
CarID
I wish to have the relationship as many cars to one customer. Would I need a 3rd 'link' table or is there a way to do this without another table? Sorry for such a simple question
Remove CarID from your Customer table. Make CustomerID in the Car table a foreign key to Customer, and remove any existing unique constraints on that column.
Remove CarID from your customers table and you would be set. Just be sure to have the CustomerID field in the Car table be a Foreign Key.

Defining Multiple Foreign Keys in Visual Studio

I have a basic database schema as follows (dumbed down so it's easy to read):
[Staff]
StaffId (pk)
FirstName
LastName
[RosterEvent]
EventId (pk)
StartDate
EndDate
[StaffEvents]
StaffId (pk)
EventId (pk)
Ok so, many Staff can have many RosterEvents, which is why I added the StaffEvents table. It resolves the many-to-many relationship. However I do not know how to define the foreign keys.
In Visual Studio, how do I define these as foreign keys using the Table Designer? If I try to add the relationship using the Foreign Key Relationships dialog box, I get the error message "The columns in table 'StaffEvents' do not match an existing primary key or UNIQUE constraint". Even though the UNIQUE constraint has been applied to all primary keys on every table.
Help is much appreciated! Thanks!
In the table designer you can click the row headers on the side of the two columns you want and click the primary key icon on the toolbar.
Are your PK actually marked as Primary Keys or just UNIQUE? Are they the same data-type?
All primary keys on every table are marked as PK and UNIQUE. They are also all of type int.
This is how I am trying to set up the relationship at the moment.
From the Staff table I click the 'Relationships' toolbar button.
I click 'Add'
I click on the (...) from the 'Tables and Columns Specifications' property.
I select 'StaffEvents' as the primary key table.
I select 'StaffId' from the drop down box.
When I click OK, I get the error message "The columns in table 'StaffEvents' do not match an existing primary key or UNIQUE constraint".

Resources