Usage of Foreign Key - sql-server

I'm trying to learn SQL Server and got confused about use of foreign key. I'm good with creation, altering and dropping the foreign keys., by my doubt is that when the Foreign key is useful!
1st table is 'subject', having 'subject'(primary key) and 'teacher' in it.
2nd table is 'Class', having 'Class'(primary key) and 'Floor'.
I made the 3rd table 'Details' with 'class' and 'subject'.
'details.subject' is the foreign key reference to 'subject.subject AND 'details.class' is the foreign key reference to 'class.class'. Now Im confused how can I see all the details in one excecution?
SELECT *
FROM Details
is giving only class and subject from the table 'Details'. But I want to get " details.class, class.floor, details.subject, subject.teacher " when I run a singe query. If we get the mentioned output only if we use 'JOINS', then why we should use 'Foreign Key' :o
I think you understand my doubt.. Im stuck, Please help :p

It is used to prevent actions that would destroy links between tables. The FOREIGN KEY constraint also prevents invalid data from being inserted into the foreign key column, because it has to be one of the values contained in the table it points to.
Also you if you have foreign key relation ship between 2 tables. And you have enabled cascade on deletion then if parent row deleted it will automatically deletes related row in child table.

Related

Integrity constraint violation in cakephp

I have created table with Composite Primary Key, but while edit giving Integrity constraint violation error in cakephp.
Integrity constraint violation : 1062 Duplicate entry while saving Composite Primary Key data of model
Integrity constraint violations mean that you are trying to save a duplicate of a Unique value in the database. Primary Keys have to be Unique.
Do you have your Primary Key field in your database set to auto increment? If you do not, that may be your problem.
Otherwise, when you insert a record, it's probably going to insert a row with PK of 0. Then when it tries to insert another record, it will try to insert another row with PK of 0, thus not being unique, and throwing the Integrity Constraint violation.
However
You mentioned that you are doing an edit. If you are doing an edit, then you are not passing the edited rows Primary Key when you are saving it to the database, so cake tries to do a CREATE instead, thus resulting in another duplicate row ID.
Make sure you do this:
$this->Model->id = $id; // Where $id is the Primary Key of the row being edited.
Conversely, you can also do this:
$data['Model']['id'] = $id;
$this->Model->save($data);
You can capture the $id by either storing it as a hidden field in your edit form, or as a URL parameter passed to the action.

sql server creating foreign key as one to one not one to many (linq)

I have set up my tables like so:
Table A:
Id
[...]
Table B:
Id
AId
[...]
I have a foreign key created as
FK_TableB_TableA where primary key table is Table A and its primary key is Id and the foreign key table is TableB and its foreign key is AId...
However, when I update my dbml for linq TableB is defined as an entityref instead of an entityset...
Adding a foreign key should generate a one-to-many relationship correct?
This is very generic but if I need to add more detail please let me know!
Didn't figure out why this was happening however on the dbml there was no association created between the two tables for whatever reason - therefore I just added the association.

Creating New Foreign Key (SQL Server)

I am having a bit of trouble creating a foreign key in my DB. Here is a paraphrased model of what my tables look like:
NOTE
* (PK) NOTE_ID BIGINT
* TITLE VARCHAR(200)
* DATE DATETIME
* SERIES_ID BIGINT
SERIES
* (PK) SERIES_ID BIGINT
* TITLE VARCHAR(200)
* DESCR VARCHAR(1000)
I am trying to create a "has a" relationship between NOTE and SERIES by SERIES_ID. I thought that setting up a foreign key between the two tables by SERIES_ID would be the solution, but when I attempt to create it I get the following error:
ERROR: There are no primary or candidate keys in the referenced table 'dbo.SERIES' that match the referencing column list in the
foreign key 'FK_SERIES_NOTE'. Could not create constraint
I'm using the web database manager that comes with the GoDaddy SQL Server I set up, so I'm not sure what the underlying query it's trying to use or I would post it.
At the end of the day, this is all to create a relationship so that the NHibernate mappings for my Note object will contain a one-to-one relationship to a Series object. I may not even be trying to tackle this the correct way with the foreign key, though.
Am I going about this the correct way?
EDIT:
In an attempt to pair down the tables to a more simple example, I removed what I thought to be several non-critical columns. However, I ended up leaving a field that was actually a part of the composite primary key on the series table. So, because I was trying to assign the foreign key to only one part of the composite key, it was not allowing me to do so.
In the end, I have taken another look at the structure of my table and found that I don't actually need the other piece of the composite key - and after removing, the assignment of the foreign key works great now.
If you can, you may try running the following statement in a query analyzer and see the resulting error message (I guess #Damien_The_Unbeliever is right ) :
ALTER TABLE NOTE ADD CONSTRAINT FK_SERIES_NOTE
FOREIGN KEY (SERIES_ID) REFERENCES SERIES(SERIES_ID)
--ON DELETE CASCADE
-- uncomment the preceding line if you want a delete on a serie
-- to automatically delete all notes on this serie
Hope this will help

SQL Server: Unable to create relationship

I was trying to create a table that has a one to many relationships. but it seems that adding a foreign key in Personal is not working. I am trying to link a Personal Information table to a address table? what is the solution for this error?
Address table saved successfully
Personal table
Unable to create relationship 'FK_Personal_Address'.
Cascading foreign key 'FK_Personal_Address' cannot be created where the
referencing column 'Personal.ID' is an identity column. Could not
create constraint. See previous errors.
The primary key in the Person table is presumably an identity. This is an auto-incrementing integer field.
You need to make the foreign key in the address table of type int, not identity. It will hold integers which correspond to Person records, but you don't want the foreign key to auto-increment. For each record in the child table (address) you will set a specific value for the foreign key indicating to which parent record (Person) it belongs.
Example:
INSERT person (firstname, lastname) VALUES ('John', 'Smith')
This will insert the new person record and the field personid will be filled automatically because it is an IDENTITYfield.
Now to insert an address from John Smith you need to know his personid. For example:
-- Say, for example, personid of John Smith is 55
INSERT address (personid, street, city) VALUES (55, 'High Street', 'London')
So in the person table the personid is generated automatically but in the address table you specify the value that matches an existing person. That's the whole point of a foreign key.
Without more information about your schema it's hard to guess the problem.
I made sure to follow identity, int and primary key discussed in above answer. However, I was still getting the same error.
'xReason' table saved successfully
'xAddress' table
- Unable to create relationship 'FK_xAddress_xReason'.
The ALTER TABLE statement conflicted with the FOREIGN KEY constraint "FK_xAddress_xReason". The conflict occurred in database "databaseName", table "dbo.xReason", column 'xReasonID'.
This error resolved when I inserted some data into a Reason table. (table that had a primary key)
If you read this far, this might be your problem.
Without seeing the structure of the tables in the question, I believe the most likely cause is the column in your child table (Address) is marked as an Identity column. In a foreign-key relationship, the parent determines the value of the field, not the child. The column may be the PK in the child table, but not an Identity.
it seem that you try to create a foreign key on Personal.ID related to itself.
You probably want to do something like :
ALTER TABLE Adress WITH NOCHECK ADD CONSTRAINT [FK_Adress_Personnal] FOREIGN KEY(Personal_Id)
REFERENCES Personal (ID)
I got the same error with adding foreign key constraints to one of my tables.
I found the workaround was to add it WITH NOCHECK. why I was able to add the other two foreign keys WITH CHECK but not the third foreign? I found that it was not the table but the order of the foreign key to be added. Any insight to this will be much appreciated.

SQL Server: how to reference a foreign key to another table where the key is named differently

Trying to write the script to reference a foreign key in another table that is named differently. Here's part of my script, see if you can figure out what im trying to do, I don't know a better way to explain it:
ALTER TABLE journal
ADD CONSTRAINT journal_authorid_FK FOREIGN KEY(author_id) REFERENCES employee.emp_id;
as you can see, the author_id in one table references the emp_id primary key in another table. Reason being is that there is already a key in this table called emp_id.The emp_id FK in this table will be used to identify who this journal entry pertains to. The author_id is the person that made the entry. Obviously they are both located on the employee table. How do I make this relationship?
I believe the syntax is:
ALTER TABLE journal
ADD CONSTRAINT journal_authorid_FK FOREIGN KEY(author_id) REFERENCES employee(emp_id);

Resources