Two FK to one PK - sql

I'm using SQL Server Express 2012 and trying to make two relatonships, two FKs from the same table to one PK in another table.
The relationship seems to work because it shows up in the database diagram but when I try to save the changes, I receive the following error:
'Members' table saved successfully
'BookedResources' table
- Unable to create relationship 'FK_BookedResourcesMemberId_MembersMemberId'.
The ALTER TABLE statement conflicted with the FOREIGN KEY constraint "FK_BookedResourcesMemberId_MembersMemberId". The conflict occurred in database "resursBokning2", table "dbo.Members", column 'MemberId'.
MemberId in Members is the PK.
BookedResouce.EditedBy (FK) -> Member.MemberId (PK)
BookedResouce.MemberId (FK) -> Member.MemberId (PK)
Anybody know what this error is about?
I've read that it should be OK to have this kind of relationship so it should work.

From the error you've provided, it looks like you tried to name both foreign keys the same. As #kinse suggests, give each foreign key relationship a unique name. Also, consider whether you need two foreign keys to the same table - it could indicate that your database model is incomplete.
I am making an assumption that Members wouldn't be editing other members, so EditedBy (a member) and MemberId appear to be unnecessary on the members table.

The error occurs because maybe you use the same name for a foreign key twice, so change the name of the second to some other value, e.g.:
FK_BookedResourcesMemberId_MembersMemberId2

Related

Logical Modeling difficulty

I have a task to design a simple database that will store information about restaurants, customers and Categories that each restorant falls in (ex. American,Indian...). The problem is that I am not sure how to model the database having the fact that every customer may have zero or more registered other
customers as friends. Whilst a customer can have many friend connections, for
each friend connection the date must be recorded.
I assume that I have to create another table called Friends that will contain the cust_id,data as attributes.
My tables are:
Restaurants(rest_id,name,address,date_opened,income_cat_id*)
Category(car_id,title,Description)
Customers(cust_id,name,address,DOB,Mobile_number)
Here is my ER Diagram, but as I said I am not sure if the Recursive relation is right for my Customers table:
Yes, you need another table to model the connections, something like:
Connection(cust_id1, cust_id2, connectdate)
Thank you a very much!
Does that mean that I have to have the following constraints in the Connection table?
CONSTRAINT pk_Connections PRIMARY KEY (cust_id1,cust_id2),
CONSTRAINT fk_Customers_Connections_cust_id1 FOREIGN KEY (cust_id1) REFERENCES Customers(cust_id)
ON DELETE CASCADE ON UPDATE CASCADE,
CONSTRAINT fk_Customers_Connections_cust_id2 FOREIGN KEY (cust_id2) REFERENCES Customers(cust_id)
ON DELETE NO ACTION ON UPDATE NO ACTION);

Last Modified By fields and foreign keys

In SQL Server 2012, I have a User table to store application users. I also have an Organization table which has a LastModifiedBy field in which I would like to store the UserID of the last person to modify the values within the table via an ASPX page. Should I create a foreign key relationship between the LastModifiedBy field and the UserID field within the Users table?
I would also like to add a LastModifiedBy field to the Users table itself. Should/can I create a self referencing foreign key constraint on this table? If this is possible, is it a horrible idea?
Any perspectives on pros and cons of creating these foreign key constraints would be greatly appreciated.
What you are describing is what foreign keys are made for. These foreign keys are at the very core of relational databases. Even if they might give a slight performance impact when inserting new rows, because it has to check if the referenced key exists, it should not be avoided.

Multiple Cascade Paths

I have a problem with multiple cascade path error. Here are my tables:
Table (Companies)
CompanyCode (PK)
....
Table (Aircraft)
AircraftRegistration (PK)
OwnerCode (FK to CompanyCode)
OperatorCode (FK to CompanyCode)
....
I simply want to update the ownercode and operatorcode foreign keys in the aircraft table when I update the primary key in companies.
Is the correct way to get around this problem to use triggers?
You can add ON UPDATE CASCADE to your foreign key definitions, then the values will automatically be updated if the referenced key (i.e. Companies.CompanyCode) is changed.
EDIT: But as you noted in the comments, this won't work for tables that have two foreign keys referencing the same column, so for those cases you would have to use a trigger or do all your updates in a 'controlled' manner, such as through a stored procedure that updates the referencing columns. Which approach is better depends on your application design and how your database is used.

Adding foreign keys to an already existing database

I'm trying to export data from an Excel spreadsheet into a fairly complex relational database. The spreadsheet indicates "foreign keys" by stating the names of other objects. (Luckily, I have some control over the spreadsheet, so I can guarantee these names are unique AND that the objects they reference actually exist).
I have a program that can recreate these tables in a MSSql database, but it can't automatically link them to each other. Besides, I don't want to use the actual names of the objects as the primary key since eventually the database will be large.
So, if I have many existing but unconnected tables which refer to each other by their "name" fields, how can I add a foreign key that links them by their IDs?
A simplified version of what I have:
Parent
ID: 1 (PK)
Name: Mary
Child
ID: 2 (PK)
Name: Jane
ParentName: Mary
And what I want to achieve:
Child
ID: 2 (PK)
Name: Jane
ParentID: 1 (FK)
Thanks for any help! I wasn't able to find an example of how to add a foreign key mapping after the fact, or on a different field.
See the ALTER TABLE syntax for MSSQL. You can come up with something like this to add the constraint to the table:
ALTER Child
ADD CONSTRAINT Child_Parent_FK FOREIGN KEY (ParentID) REFERENCES Parent(ID)
Then once the constraint is in, try something like:
UPDATE Child
SET ParentID = (SELECT ID FROM Parent WHERE Name = ParentName)
That should work if you can guarantee the Name of the Parent is unique. Otherwise you can add LIMIT 1 to the end of the query. But if there are multiple Parents with the same Name, you're going to need to add extra logic (which isn't specified in your original post).
Since you're going to be doing this regularly, I think you should import into a staging table. I like to isolate staging tables in their own schema.
Use the staging table to retrieve or generate the keys you need, then insert/update your OLTP tables based on the data in the staging table. Finally, truncate the staging table.

Database: One To Many (or One To None) relationship

Im modelling a database in MSSQL 2008.
I have 4 tables.
**User**
userID
userName
**NewsCategory**
newsCategoryID
newsCategoryName
**News**
newsID
newsText
newsCategoryID
**Subscription**
userID
categoryID
I understand that I should have foreign keys between the News and the Category tables. But what should I do with the supscriptions? Should I have a Foreign Key between User and Subscription tables though it's not mandatory to subscribe for something?
Yes you should. Foreign key is used for be sure, that Subscription is created for existing user. Foreign key does not mean, that user should be subscribed on something.
Yes you should have this foreign key because it will prevent a Subscription from existing that does not map to a real user id.
It acts as a constraint on your data.
Subscription is a link (many-many) table and "not mandatory" means there will no row for that user or that user/category.
The foreign key is required to enforce data integrity when you do have subscriptions which will be one or more rows.
Note: In optional parent-child type relationships the FK column(s) will be NULLable to capture "non mandatory". In link tables this is captured by row non-existence
Yes, you should add Foreign keys between User and SubCription tables with Subscription table.
Foreign key contraints are for the validating of adding wrong information to the database. For example, in your Subscription table, there shouldn't be userIDs which are not in the User table and there should be CategoryIDs which are not in the NewsCategory table. These contraints will do the validation for you even if you don't do the validation at the user interface end.
You've gotten some good answers. Let me try to add another.
A SUBSCRIPTION requires both a subscriber and a category. Therefore, each of these columns should not allow nulls. Preventing nulls is not the same thing as a foreign key constraint.
It should also be impossible to insert a row into SUBSCRIPTIONS if the user does not already exist in the USERS table; and it should be impossible to insert a row into SUBSCRIPTIONS if the category does not already exist in the CATEGORIES table. To enforce these rules your SUBSCRIPTIONS table requires two foreign key constraints:
ALTER TABLE SUBSCRIPTIONS ADD CONSTRAINT FK_SUBSCRIPTIONS_USERS FOREIGN KEY(userid) REFERENCES USERS(userid)
ALTER TABLE SUBSCRIPTIONS ADD CONSTRAINT FK_SUBSCRIPTIONS_CATEGORIES FOREIGN KEY(categoryid) REFERENCES CATEGORIES(categoryid)
When you create a foreign key constraint on a table, you are in effect saying to the database engine: make sure that any value that gets inserted into this table already exists in that other table. BTW, a requirement for the constraint to be created is that a unique constraint must be in effect on the column(s) referenced in that table; typically, the referenced column(s) of that table will be the primary key of that table.
By creating a foreign key constraint, you are not saying to the database engine: make sure a row gets inserted into this table. It is quite possible (though it would be unusual) that this table has no rows in it whatsoever. The foreign key constraint simply makes sure that any value that does get inserted into this table has a counterpart in that table.