How to add MSSQL constraint to limit the number of related tables - sql-server

I have a parent table with a relationship to each of four child tables. The primary key of the parent table forms both the primary and foreign key for the child tables. For any given row in the parent table, there can only be two child tables associated, either GradeOneA and GradeOneB or GradeTwoA and GradeTwoB. How can I add a constraint that if an ID in the parent table matches an ID in the GradeOneA table then it cannot also match an ID in the GradeTwoA table and vice versa?

You can do this with a CHECK constraint that calls a function on each of the child tables. The function checks the other child tables to see how many of them have the same PK/FK. The constraint looks at the return value and decides whether the row should be allowed.

Related

non identifying relationship in non key attribute

I wish to define a relationship between a parent->child table.
The field in the parent table is a non key attribute(relation_field_A). I would like to define a relationship between the parent table and the child table via the relation_field_A field. I want to ensure that a value in Table_B.relation_field_A exists in the Table_A.relation_field_A.
What I want is a non-identifying relationship between the parent and child table. Is this possible?
Table_A
------
Key_A - PK
field1
feild2
relation_field_A
Table_B
-------
Key_B - PK
field1
field2
relation_field_A
If you want to make a foreign key from Table_B to Table_A, then the column in Table_A must have at least an unique index
create unique nonclustered index UX_TableA on table_A (relation_field_A)
See this example
Without this, you would allow a child to have a link to more than one parent, which is not allowed. In a master-child relationship a parent can have 0, 1 or many childs, and a child can have only one parent.
If that is not what you want than you maybe are after a many to many relation ship ?
For that you need a third table which links both together.
There are many examples on google about many-to-many relationships
And if you really just want to ensure that the relation-field-a in Table_B exists in Table_A without an unique index than you cannot achieve this with a foreign key, you could write a trigger on both tables to try to ensure this.
But honestly, it seems like a design flaw has been made somewhere here.

Can someone explain this statement (foreign key) of a table

CREATE TABLE genres
(
genre_id INT GENERATED BY DEFAULT AS IDENTITY NOT NULL,
genre VARCHAR(255) N[enter image description here][1]OT NULL,
parent_id INT NULL,
-- Will be thankful to you for explaining the 3 lines below
PRIMARY KEY (genre_id),
CONSTRAINT fk_parent
FOREIGN KEY(parent_id) REFERENCES genres(genre_id)
);
PRIMARY KEY(genre_id) - means that at most one row in the table GENRES can have a specific value. In other words, for every row in the table, the value in GENRE_ID column will be unique. Additionally the value in the column cannot be null, and that value serves to identify the row uniquely without needing any other value to identify the row. The DDL shows that the database will generate the value for the GENRE_ID column by default.
The "CONSTRAINT fk_parent FOREIGN KEY(parent_id) REFERENCES genres(genre_id) )" means that the database-manger
will enforce that if column PARENT_ID is not null then the value in this column must be an existing value in a row in the GENRES table. Another way of thinking about this is that the database-manager is asked to maintain a parent-child relationship, so a genre may have sub-genres (i.e. a genre may have child genres). So the database manager would not let you specify that a particular genre was a sub-genre of a non-existent parent genre.
The database manager might also enforce the relationship is valid over time, for example it might prevent a delete or update action if that delete would produce orphan rows (i.e. child rows with no parent row) , or it may set such parent_id values to null, depending on the DDL and Db2-version/platform.
Answer:Self Referencing Foriegn Key
https://www.red-gate.com/simple-talk/sql/t-sql-programming/questions-about-primary-and-foreign-keys-you-were-too-shy-to-ask/

How to use foreign key in two tables based on a flag column?

I have a parent table Tree and two child tables Post and Department.
Based on the Flag column this relation must be set.
How can I do this?
You cannot do that with foreign keys. You could implement a trigger which would check for the ReferenceID presence either on the Post or on the Department table based oh the Flag column.
Although the best approach would be to change your design to have 2 nullable columns as follows, and ensuring only one of them has a value:
CREATE TABLE Tree (
ID Integer NOT NULL,
PostID Integer REFERENCES Post(ID),
DepartmentID Integer REFERENCES Department(ID),
Flag INTEGER NOT NULL
)

How to use foreign key of sqlite to link three table 1->2->3 different column

I am having three table i want to link all three table together.
for example :
table1 : create table master (sr_no int,int,name text);
table2 : create table child1 (sr_no int,emplno int,last_name text,foreign key(sr_no) refernces master(sr_no) on delete cascade on update cascade);
table3 : create table child2 (Em int,phone text,foreign key(Em) refernces child1(emplno) on delete cascade on update cascade);
But when inserting data into table3 its show ===> Error: foreign key mismatch
please tell me whts problem
thank you
http://www.sqlite.org/foreignkeys.html#fk_indexes
Foreign key DML errors are may be reported if:
The parent table does not exist, or
The parent key columns named in the foreign key constraint do not exist, or
The parent key columns named in the foreign key constraint are not the primary key of the parent table and are not subject to a unique constraint using collating sequence specified in the CREATE TABLE, or
The child table references the primary key of the parent without specifying the primary key columns and the number of primary key columns in the parent do not match the number of child key columns.
Is emplno the primary key in child2?
The documentation says:
the parent key columns must be collectively subject to a UNIQUE constraint or have a UNIQUE index
Add a UNIQUE constraint to child1'S emplno field, or create a separate index on it.

on delete cascade is deleting entire child table

I have two tables:
Parent, which has a primary key (parentID) and some other fields of type varchar(50) and Child which is as follows:
childID, primary key
parentID, foreign key references Parent (parentID)
otherID, foreign key to another table
If I delete a row from Child, no problem.
If I delete a row from Parent, I get a foreign key constraint error on Child -- good, that's correct.
Now, I modify the relationship for the parentID key and set delete to cascade instead of No Action
(I'm using the 2008 server studio, right-clicking on column, choose Modify, then right click on the table design and choose Relationships. I then choose the relationship for the Parent/Child tables and open the Insert/Update Specification section under Table Designer)
If I delete a row from Child, again, no problem.
If I delete a row from Parent, ALL the rows of the child table are deleted, even through most of them point to other parentIDs.
I inherited this DB and all it's tables. Is there some properties settings I'm missing? From what I've read, the cascade delete should ONLY delete the child rows that point to the single parentID I deleted from Parent.
Thanks.
Ben
Right, the delete should only delete rows related to the deleted "parent".
Take a look at the cascading delete setup, and also look for triggers that may be incorrectly written.
Try setting SetNull instead of cascade, which results setting your child table column (where Parent Table's key exit) to NULL.

Resources