SQL Server: Unable to create relationship - sql-server

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.

Related

SQL Server having a column as both PK and FK

I have not done much database design work and I was searching around for some example.
While I know the difference from a primary and foreign key, one thing that caught be off guard was that even if a Table has a primary key and is used as a foreign key in another table, as I was used the GUI SSMS tools, I noticed that I sometime end up having this
PhoneID (PK, int, not null)
While my User table
UserId(PK,FK, int, not null)
BOTH of these tables have these ID's as primary keys in those tables, along with foreign keys in other tables, but why does one of them have "PK,FK" obviously I accidentally created it, but should it be like that?
It is Possible for a Primary key to be a Foreign Key as well at the same time.
But looking at you database design, In your case I dont think it was intentional it was done by mistake. And if it wasnt done by mistake then you need to fix it.
In your dbo.PhoneType Table the column PhoneTypeID needs to be a Primary key only not a Foreign key. My guess is this was done by mistake, you wanted to create a Foreign key in your dbo.Phone table on column PhoneTypeID referencing PhoneTypeID column in dbo.PhoneType table. But somehow you end up create a foreign key constraint on the Primary key column of the dbo.Phontype table.
This Design contradicts constraints.
In simple english : The foreign Key Constraint on your dbo.PhoneType(PhoneTypeID) enforces that you cannot have a PhoneTypeID in dbo.PhoneType table unless it exists in PhoneTypeID column of dbo.Phone table.
On the other hand Foreign Key Constraint on dbo.Phone(PhoneTypeID) enforces that you cannot have a PhoneTypeID in dbo.Phone unless it exists in dbo.PhoneType(PhoneTypeID).
and same is true for the UserID column in dbo.Users table.
Solution
You need to drop the following Constraints to make it work properly.
1) In dbo.PhoneType table Drop Foreign key constraint referencing
PhoneTypeID column in dbo.phone table.
2) In dbo.Users Table drop the Drop Foreign key constraint referencing
UserID column in dbo.phone table.
It's entirely possible, yes. A primary key of a table could also be a foreign key referencing another table.
In your case, I'm not exactly sure what you did. You can check the constraints to see which column the UserId column is referencing.
As an additional note, simply adding a foreign reference to a table does not implicitly make that column a foreign key on another table. For example, just because you add FK_PhoneTypeID to the Phone table, SQL Server does not automatically make PhoneTypeID column in the PhoneType table a FK. In your statements, somewhere, it's possible that you made assignments to other columns, or even to themselves.

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.

Database table constraints query

Can a relational table have constraints related to another table? If yes, please provide an example also
Yes, think of foreign key constraint. Foreign key constraint is related to another table.
For example, consider following table
Address (Addressid (PK), AddressLine1, City, State_cd (FK))
State (State_cd(PK), State_name)
Note here that State_cd which is in Address table is related to another table (State).
Hope this is clear

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);

Bidirectional foreign key constraint

I'm thinking of designing a database schema similar to the following:
Person (
PersonID int primary key,
PrimaryAddressID int not null,
...
)
Address (
AddressID int primary key,
PersonID int not null,
...
)
Person.PrimaryAddressID and Address.PersonID would be foreign keys to the corresponding tables.
The obvious problem is that it's impossible to insert anything into either table. Is there any way to design a working schema that enforces every Person having a primary address?
"I believe this is impossible. You cannot create an Address Record until you know the ID of the person and you cannot insert the person record until you know an AddressId for the PrimaryAddressId field."
On the face of it, that claim seems SO appealing. However, it is quite propostrous.
This is a very common kind of problem that the SQL DBMS vendors have been trying to attack for perhaps decades already.
The key is that all constraint checking must be "deferred" until both inserts are done. That can be achieved under different forms. Database transactions may offer the possibility to do something like "SET deferred constraint checking ON", and you're done (were it not for the fact that in this particular example, you'd likely have to mess very hard with your design in order to be able to just DEFINE the two FK constraints, because one of them simply ISN'T a 'true' FK in the SQL sense !).
Trigger-based solutions as described here achieve essentially the same effect, but those are exposed to all the maintenance problems that exist with application-enforced integrity.
In their work, Chris Date & Hugh Darwen describe what is imo the true solution to the problem : multiple assignment. That is, essentially, the possibility to compose several distinct update statements and have the DBMS act upon it as if that were one single statement. Implementations of that concept do exist, but you won't find any that talks SQL.
This is a perfect example of many-to-many relationship. To resolve that you should have intermediate PERSON_ADDRESS table. In other words;
PERSON table
person_id (PK)
ADDRESS table
address_id (PK)
PERSON_ADDRESS
person_id (FK) <= PERSON
address_id (FK) <= ADDRESS
is_primary (BOOLEAN - Y/N)
This way you can assign multiple addresses to a PERSON and also reuse ADDRESS records in multiple PERSONs (for family members, employees of the same company etc.). Using is_primary field in PERSON_ADDRESS table, you can identify if that person_addrees combination is a primary address for a person.
We mark the primary address in our address table and then have triggers that enforces only record per person can have it (but one record must have it). If you change the primary address, it will update the old primary address as well as the new one. If you delete a primary address and other addresses exist, it will promote one of them (basesd ona series of rules) to the primary address. If the address is inserted and is the first address inserted, it will mark that one automatically as the primary address.
The second FK (PersonId from Address to Person) is too restrictive, IMHO. Are you suggesting that one address can only have a single person?
From your design, it seems that an address can apply to only one person, so just use the PersonID as the key to the address table, and drop the AddressID key field.
I know I'll probably be crucified or whatever, but here goes...
I've done it like this for my "particular very own unique and non-standard" business need ( =( God I'm starting to sound like SQL DDL even when I speak).
Here's an exaxmple:
CREATE TABLE IF NOT EXISTS PERSON(
ID INT,
CONSTRAINT PRIMARY KEY (ID),
ADDRESS_ID INT NOT NULL DEFAULT 1,
DESCRIPTION VARCHAR(255),
CONSTRAINT PERSON_UQ UNIQUE KEY (ADDRESS_ID, ...));
INSERT INTO PERSON(ID, DESCRIPTION)
VALUES (1, 'GOVERNMENT');
CREATE TABLE IF NOT EXISTS ADDRESS(
ID INT,
CONSTRAINT PRIMARY KEY (ID),
PERSON_ID INT NOT NULL DEFAULT 1,
DESCRIPTION VARCHAR(255),
CONSTRAINT ADDRESS_UQ UNIQUE KEY (PERSON_ID, ...),
CONSTRAINT ADDRESS_PERSON_FK FOREIGN KEY (PERSON_ID) REFERENCES PERSON(ID));
INSERT INTO ADDRESS(ID, DESCRIPTION)
VALUES (1, 'ABANDONED HOUSE AT THIS ADDRESS');
ALTER TABLE PERSON ADD CONSTRAINT PERSON_ADDRESS_FK FOREIGN KEY (ADDRESS_ID) REFERENCES ADDRESS(ID);
<...life goes on... whether you provide and address or not to the person and vice versa>
I defined one table, then the other table referencing the first and then altered the first to reflect the reference to the second (which didn't exist at the time of the first table's creation). It's not meant for a particular database; if I need it I just try it and if it works then I use it, if not then I try to avoid having that need in the design (I can't always control that, sometimes the design is handed to me as-is). if you have an address without a person then it belongs to the "government" person. If you have a "homeless person" then it gets the "abandoned house" address. I run a process to determine which houses have no users

Resources