Adding Foreign Key, SQL SERVER 2008 - tsql

I am trying to add a foreign key to a table, and it give me the following error:
There are no primary or candidate keys in the referenced table 'tbl_Person' that match the referencing column list in the foreign key 'P_ID'.
I have a tbl_Person, which is defined as:
P_ID INT (Primary Key)
f_Name,
l_Name
the other table is a comments table which is defined as:
C_ID INT,
Comments,
P_ID (should be the foreign key)
Trying to make a one to many relationship table, so when the user add a comment, it is referenced back to him, also, he can add onto the comments without initializing a new comment. Hopefully that makes a little sense.
Ex: Randy Bing enter "I love SQL", his ID is 1, f_Name is Randy, l_Name is Bing, his comments are "I love Sql". His comments should store a unique ID, as well as import his P_ID.
Later on when Randy wants to add onto the comment with the same C_ID where P_ID matches him without creating a new C_ID.
Here is the Code:
ALTER TABLE tbl_Comments
ADD CONSTRAINT P_ID
FOREIGN KEY (P_ID)
REFERENCES tbl_Person(P_ID)
Am I close to being on the right track?

This error usually means the datatypes are different between "Comments" and "Person", assuming this is the actual message
The SQL should be this
ALTER TABLE tbl_Comments WITH CHECK ADD
CONSTRAINT FK_Comments_Person FOREIGN KEY (P_ID) REFERENCES tbl_Person (P_ID)
This matches what you added. So:
check datatypes are both int
ensure P_ID is primary key on tbl_Person
(Edit, Dec 2011) collation and length must be the same for varchar columns too

In Object Explorer, connect to an instance of Database Engine.
On the Standard bar, click New Query.
The example creates a foreign key on the column TempID and references the column SalesReasonID in the Sales.SalesReason table.
USE AdventureWorks2012;
GO
ALTER TABLE Sales.TempSalesReason
ADD CONSTRAINT FK_TempSales_SalesReason FOREIGN KEY (TempID)
REFERENCES Sales.SalesReason (SalesReasonID)
ON DELETE CASCADE
ON UPDATE CASCADE
;
GO

the name of your constraint, p_id,
clashes with the name of the p_id column

Related

How to alter a foreign key in postgresql

I created a table in PostgreSQL with a foreign key constraint.
I dropped the table to which the foreign key belongs. Now how to alter the table or how to defer the foreign key present in the table?
To clarify:
I have a table named test. It has a column called subjectName, which is a foreign key of subject Table. Now I dropped subject table. How to remove the FK constaint on table test
Assuming the following tables:
create table subject
(
name varchar(10) primary key
);
create table test
(
some_column integer,
subject_name varchar(10) not null references subject
);
there are two scenarios what could have happened when you dropped the table subject:
1. you didn't actually drop it:
drop table subject;
ERROR: cannot drop table subject because other objects depend on it
Detail: constraint test_subject_name_fkey on table test depends on table subject
Hint: Use DROP ... CASCADE to drop the dependent objects too.
2. you did drop it, then the foreign key is gone as well.
drop table subject cascade;
NOTICE: drop cascades to constraint test_subject_name_fkey on table test
which tells you that the foreign key constraint was automatically dropped.
Perhaps your question in not exactly what you mean. Are you wanting to remove the which was a foreign key from the table. As amply indicated if you dropped the parent table then the FK is also dropped. However the column itself is not dropped from the child table. To remove that you need to alter the table.
alter table test drop column subject_name;
See demo here

SQL database design for tags. How to handle missing relation between two tables?

I have three tables in a PostgreSQL database (one for storing articles, one for all tags, and one for the relation between the two):
table: article
columns: article_id, title, content
table: tag
columns: tag_id, name
table: article2tag
columns: article_id, tag_id
For now I only have two tags in the tag table:
tag (table)
-----------
tag_id name
1 apple
2 orange
I have an article (the one with ID 1) tagged with the two tags: apple and orange:
article2tag (table)
--------------------
article_id tag_id
1 1
1 2
But let's say one of the tags in the tag table will be removed, for example the tag named apple, now tag_id in article2tag will point to an inexistent tag.
What is the proper way (if there is one) to handle this situation?
That can be handled with foreign key constraints.
ALTER TABLE article2tag
ADD FOREIGN KEY (article_id)
REFERENCES article
(article_id);
ALTER TABLE article2tag
ADD FOREIGN KEY (tag_id)
REFERENCES tag
(tag_id);
That way, if you try to delete a tag that is still used in an article you'll get an error and cannot delete the tag.
You can also specify that, if a tag is deleted it will be removed from all articles with ON DELETE CASCADE.
ALTER TABLE article2tag
ADD FOREIGN KEY (tag_id)
REFERENCES tag
(tag_id)
ON DELETE CASCADE;
You can also use that for the foreign key to article.
You probably don't know about primary keys too, so you might encounter an error when trying to create the foreign key constraints about the referenced column not being unique. In that case add primary key constraints to article and tag.
ALTER TABLE article
ADD PRIMARY KEY (article_id);
ALTER TABLE tag
ADD PRIMARY KEY (tag_id);
You should also define a primary key for articel2tag analogously.
ALTER TABLE article2tag
ADD PRIMARY KEY (article_id,
tag_id);

Can I have a foreign key to a parent table in PostgreSQL?

I'm using inheritance and I ended up having a problem.
If I run:
select count(*) from estate_properties where id = 86820;
I get 1.
But when I try to run this:
insert into property_images (binary_image, name, property_id) values (16779, 'IMG_0096.jpg', 86820)
I get:
********** Error **********
ERROR: insert or update on table "property_images" violates foreign
key constraint "property_images_property_id_fkey" SQL state: 23503
Detail: Key (property_id)=(86820) is not present in table
"estate_properties".
Also ID on estate_properties is SERIAL.
Note: Another table apartments inherits from estate_properties, and 86820 was added to it. Would that make a difference? Also why would it I still have the ID in the parent table and I can select if from there.
Edit:
Looking more closely at the documentation:
http://www.postgresql.org/docs/9.5/static/ddl-inherit.html
I want to achieve this:
5.9.1. Caveats
Specifying that another table's column REFERENCES cities(name) would
allow the other table to contain city names, but not capital names.
There is no good workaround for this case.
EDIT2:
Here is the declaration of the foreign key:
CONSTRAINT property_images_property_id_fkey FOREIGN KEY (property_id)
REFERENCES estate_properties (id) MATCH SIMPLE
ON UPDATE NO ACTION ON DELETE NO ACTION
Apparently the answer is here:
Foreign keys + table inheritance in PostgreSQL?
A foreign key can point to a table that is part of an inheritance hierarchy, but it'll only find rows in that table exactly. Not in any parent or child tables. To see which rows the foreign key sees, do a SELECT * FROM ONLY thetable. The ONLY keyword means "ignoring inheritance" and that's what the foreign key lookup will do

Why does this foreign key using inheritance not work? [duplicate]

This question already has answers here:
PostgreSQL foreign key not existing, issue of inheritance?
(2 answers)
Closed 8 years ago.
create table abstract_addresses (
address_id int primary key
);
create table phone_numbers (
phone_number text not null unique
) inherits (abstract_addresses) ;
create table contacts (
name text primary key,
address_id int not null references abstract_addresses(address_id)
);
insert into phone_numbers values (1, '18005551212'); --works
select * from abstract_addresses;
address_id
1
select * from phone_numbers;
address_id phone_number
1 18005551212
insert into contacts values ('Neil', 1); --error
I get this error message:
ERROR: insert or update on table "contacts" violates foreign key constraint "contacts_address_id_fkey"
SQL state: 23503
Detail: Key (address_id)=(1) is not present in table "abstract_addresses".
Just a bad use-case for postgresql table inheritance?
Per the caveats in the docs:
A serious limitation of the inheritance feature is that indexes (including unique constraints) and foreign key constraints only apply to single tables, not to their inheritance children. This is true on both the referencing and referenced sides of a foreign key constraint.
http://www.postgresql.org/docs/current/static/ddl-inherit.html
To do what you want:
Create a table with only an id — like you did.
Don't use inheritance. Really don't. It's useful to partition log tables; not for what you're doing.
Make phone number ids default to nextval('abstract_addresses_address_id_seq'), or whatever the sequence name is.
Add a foreign key in phone_numbers referencing abstract_addresses (address_id). Make it deferrable, initially deferred.
Add an after insert trigger on phone_numbers that inserts a new row in abstract_addresses when needed.
If appropriate, add an after delete trigger on phone_numbers that cascade deletes abstract_addresses — make sure it occurs after the delete, else affected rows will report incorrect values when you delete from phone_numbers.
That way, you'll have an abstract_address for use in occasional tables that need such a thing, while still being able to have a hard reference to phone_numbers where the latter is what you actually want.
One caveat to be aware of: it doesn't play well with ORMs.

How to tell PostgreSQL not to verify datatype

I have a table like:
CREATE TABLE test(
id integer not null default nextval('test_id_seq'::regclass),
client_name_id integer not null
);
Foreign-key constraints:
"test_client_name_id_fkey" FOREIGN KEY (client_name_id) REFERENCES company(id) DEFERRABLE INITIALLY DEFERRED
and company table:
CREATE TABLE company(
id integer not null default nextval('company_id_seq'::regclass),
company_name character varying(64) not null
)
Now I have trigger on test table which fetch id from company table using provided value client_name_id which is string by matching it with company_name. but when I insert record PostgreSQL return error that client_name_id is string and int required which is true.
How can I tell PostgreSQL not to verify inserted row as I have taken care of it in my triggers.
What you are trying to do is very unorthodox. Are you sure, this is what you want? Of course, you cant enter a string (with non-digits) into an integer column. No surprise there, right? If you want to enter the text instead, you'd have to add a text column instead - with a fk-constraint to company(company_name) if you want to match your current layout.
ALTER TABLE test ALTER DROP COLUMN client_name_id; -- drops fk constraint, too
ALTER TABLE test ADD COLUMN client_name REFERENCES company(company_name);
You would need a UNIQUE constraint on company.company_name to allow this.
However, I would advise to rethink your approach. Your table layout seems proper as it is. The trigger is the unconventional element. Normally, you would reference the primary key, just like you have it now. No trigger needed. To get the company name, you would join the table in a SELECT:
SELECT *
FROM test t
JOIN company c ON t.client_name_id = c.id;
Also, these non-standard modifiers should only be there if you need them: DEFERRABLE INITIALLY DEFERRED. Like, when you have to enter values in table test before you enter the referenced values in table company (in the same transaction).