Implementing foreign key from two different tables - sql-server

I have three tables and from first table I want to send data column transId into second table column refId, and the same from third table I want to send data column transId into second table column refId with relation of both first and third table. How is this possible?

We can create Multiple Foreign Key On Same Column, but each of those would require the value to exist.
Eg:
Table1(1,2,3)
Table2(3,4)
You can insert the value 3 to the table3 column that have the foreign key relation to both table1 and table2(value 3 exists in both table1 and table2), but you can't insert any other values.
There is one more method to solve this, you can use an User Defined Function inside a Check constraint of table3 column to check the value exists or not in the table1 and table2

You don't need to send data from table to other. you only need to make reference from foreign_key_column (refId) to Primary_key_column (transId).
As example:
Using SQL Server
// foreign key in second table
CREATE TABLE Table2
(
refId int FOREIGN KEY REFERENCES Table1(transId)
)
// foreign key in third table
CREATE TABLE Table3
(
refId int FOREIGN KEY REFERENCES Table1(transId)
)
helped Tutorial

Seems Table2 is the master table containing column transId which references to two tables table 1 and table 2.You need to go with the creation of foreign key in table 2 and table 3 for column transId.You can use below syntax for creating relationship among tables:
--foreign key in First table
CREATE TABLE Table1
(
refId int FOREIGN KEY REFERENCES Table2(transId)
)
-- foreign key in third table
CREATE TABLE Table3
(
refId int FOREIGN KEY REFERENCES Table2(transId)
)

Related

Table with multiple relations to a single primary key

Is it possible to create multiple relations from one table, to another table?
I have a table containing purchases, each of these purchases have a origin_country and a destination_country.
I would like to have relations (as foreign keys) to a single PK on a table from these two columns from the same table.
i have tried the following queries:
alter table Purchases
add constraint FK_Purchases_OriginCountries
foreign key (FK_OriginCountryCode) references dbo.countries
go
alter table Purchases
add constraint FK_Purchases_DestinationCountries
foreign key (FK_DestinationCountryCode) references dbo.countries
go
But end up getting a conflict, I can't however find documentation that this is not possible...
[23000][547] The ALTER TABLE statement conflicted with the FOREIGN KEY
constraint "FK_Purchases_DestinationCountries". The conflict occurred
in database "Market", table "dbo.countries", column 'ID'.
Is this relationship intentionally not possible, or did i just make a mistake?
Thank you
Yes you can.
The error is not a result of trying to create two foreign keys back to a single table, that's perfectly fine. Try running this to see it work:
create table t(i int primary key);
create table u
(
j int foreign key references t(i),
k int foreign key references t(i)
);
The problem you have is that you have some data in your Purchases table where the value in the column on which you are trying to create the foreign key does not exist in the countries table's ID column.
To find them run a query like this:
select p.*
from dbo.purchases p
where not exists
(
select *
from dbo.countries
where ID = p.FK_DestinationCountryCode
)
Note that I think your column names are a little weird here, You shouldn't call a column FK_DestinationCountryCode just because it has a foreign key on it, and a "code" is not the same kind of thing as an "ID". Your purchases table's columns should probably be called DestinationCountryID and OriginCountryID.

Have a relationship between one table with one primary key and another with two primary keys?

I'm asking about this generally, but I'll give an example for illustration purposes.
Table1 has the following columns:
ID (Pk)
Order_Desc
Order_DT
Table2 has the following columns:
ID (PK)
Product_Code (PK)
Product_Desc
Is it possible for me to have relationship between Table1 and Table2. If so, how would you do this in SQL without you running into an error? Would you be able to create a relationship if the Product Code or ID was not a primary key? Instead, it was a foreign key?
Your table2 does not have two primary keys - it has ONE primary key made up from 2 columns. Any relational table NEVER has more than one primary key - it's just not possible at all.
Any FK relationship to that table must include all the columns that the PK of the referenced table has - so any FK to Table2 must include both ID and Product_Code.
It's an all or nothing proposition - either your foreign key includes all columns of the referenced tables primary key - or you cannot establish a FK-relationship.

insert rows to table with PRIMARY KEY from different tables without PRIMARY KEY sql server

I hope to explain very well my problem
I have a new table with a Primary Key.
How to insert the table from different tables?
my problem is the one table without Primary Key and I don't know how to select from table one row and insert to the new table.
Example -
new table 1
image
AssetId is Primary key
table 2
image
I need to insert one row to table 1
table 3 image
my script -
insert AssetBusStops (AssetId,StopCode,StopId,Description,ZoneId)
select Assets.Id,stops_ppp.stop_code,stops_ppp.stop_id,stops_ppp.stop_desc,stops_ppp.zone_id from Assets inner join stops_ppp
on Assets.AssetCode = stops_ppp.stop_code
Exception -
Msg 2627, Level 14, State 1, Line 11
Violation of PRIMARY KEY constraint 'PK_AssetBusStops'. Cannot insert duplicate key in object 'dbo.AssetBusStops'. The duplicate key value is (2763).
The statement has been terminated.
The value 20001 of the column AssetCode of the table Assets matches 3 rows from the table stops_ppp and these 3 rows in the result joined query have the same value 2763 in the column id.
So your query tries to insert 3 rows, not just 1 and this would create duplicates in the primary key, which is not allowed.
You should apply a filter in the results of the query, something like:
insert AssetBusStops (AssetId,StopCode,StopId,Description,ZoneId)
select top 1 ASsets.Id,
stops_ppp.stop_code, stops_ppp.stop_id, stops_ppp.stop_desc, stops_ppp.zone_id
from Assets inner join stops_ppp
on Assets.AssetCode = stops_ppp.stop_code
order by stops_ppp.stop_code
This (for your sample data) returns only 1 row (an arbitrary ow as you requested in the comments) and can be safely inserted.
A) If you don't have FK to table AssetBusStops :
Change PK Column to IDENTITY(1,1)
Remove PK value from Insert script
B) If you have FK to table AssetBusStops :
try to use Not Exists or Merge

Is it possible to ignore varchar length when setting foreign key between tables?

There are two tables in my SQL Server 2008.
CREATE TABLE TABLE1 (
field1 varchar(20) not null,
field2 int,
CONSTRAINT PK_TABLE1 PRIMARY KEY (field1)
)
CREATE TABLE TABLE2 (
Id int,
t1 varchar(10) not null
t2 ntext
CONSTRAINT PK_TABLE2 PRIMARY KEY (Id)
)
Now I want to build a foreign key on table2 with below command :
ALTER TABLE TABLE2
ADD CONSTRAINT TABLE2_FK
FOREIGN KEY (t1) REFERENCES TABLE1 (field1)
ON DELETE CASCADE ON UPDATE CASCADE
SQL Server responds that the foreign key in Table2 is different from the column field1 in Table1 in length.
Is it possible to ask SQL Server to ignore the validation of length of foreign key ?
Thank you for your answer.
No, it is not possible. From the MSDN page on CREATE TABLE, which includes a section about foreign keys:
The REFERENCES clause of a table-level FOREIGN KEY constraint must
have the same number of reference columns as the number of columns in
the constraint column list. The data type of each reference column
must also be the same as the corresponding column in the column list.
Of course, you can make a computed column that casts the VARCHAR(10) to a VARCHAR(20) and then set the foreign key.

SQL Server keys and foreign keys

If I have a primary key in table A and in table B of the same database (table B has its own primary key) I create a relationship with the primary key in table A so that a column in table B is the foreign key, does it mean that the primary key data created in the primary key column of table A will also be added to table B by virtue of it being a foreign key column or do I have to code that relationship, and if so how do I go about that?
In response to your question:
...do I have to code that
relationship, and if so how do I go
about that?
You will need to define the relationships between the two tables. Example:
ALTER TABLE tableB
ADD CONSTRAINT FK_tableB_TableA FOREIGN KEY (tableAId)
REFERENCES tableA (id) ;
When you insert a record into tableB you will still need to define tableAId is. SQL Server doesn't magically know what this should be.
So hypothetically if tableA looked like this:
1 | Some text | 1/1/2020
2 | blah blah | 6/1/2021
To insert a record in tableB that referenced record 2 you would need to do this:
INSERT INTO TableB (2,'My important information')
This assumes tableB has the following structure:
TableB
---------
Id --identity column/pk
tableAId --fk
SomeTextColumn
Your Q : does it mean that the primary key data created in the primary key column of table A will also be added to table B by virtue of it being a foreign key column
Nope, foriegn keys will not enter data into other tables. You will need a record in Table A before you insert a record referencing that foriegn key in Table B.
Q # 2 : or do I have to code that relationship, and if so how do I go about that?
insert into tableA, then insert into Table B. A trigger could be put on TableA to insert a record into TableB when data was entered into tableA had you wanted...
I'm not entirely sure what you're asking, but if you want to insert one record into table A and a related record into table B, then you have to specify the id from the table A record as the value in the foreign key field in table B.
Here's an example: table author has fields id and name.
INSERT author (id, name) VALUES (5, 'James Joyce')
Now table book has fields id, author_id and title.
INSERT book (id, author_id, title) VALUES(99, 5, 'Ulysses')
If the author's id field is automatically generated, then you would not specify it in the insert statement, and you would retrieve its value using the ##IDENTITY property.

Resources