SQL Server keys and foreign keys - sql-server

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.

Related

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

Implementing foreign key from two different tables

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

Transfer data with different type Primary key

I'm redesigning very old DB where new tables have PK type UNIQUEIDENTIFIER and old tables have INT. There are also many relationships between tables. Can anyone help with how not to lose any relationships and change PK type when transferring data?
Old Table: Item(PK - itemID(int), FK - Vendor_Id(int), and Manufacture_Id(int) Manufacture ID is not as set FK but it should be in new table.
Let's say you have empty School and Student tables with UNIQUEIDENTIFIER typed primary keys named id.
Let's say the relationship between students and schools is many-to-one, via a school_id foreign key.
The old tables are called oldSchool and oldStudent and have id columns of type int. oldStudent
also has a foreign key named school_id.
Steps to take:
Extend all new tables that are referenced to by foreign keys with an extra column called old_id of type int. In the example table School would get this extra column:
ALTER TABLE School ADD old_id int;
All foreign key columns should get a sybling column of type int, called old_original_name. In our example
Student should get an extra old_school_id column
Temporarily disable foreign key constraints:
SET foreign_key_checks = 0;
Or, if that fails, drop all the foreign keys, to recreate them later, for example:
ALTER TABLE Student DROP FOREIGN KEY fk_school_id;
Also make those foreign key columns nullable:
ALTER TABLE Student MODIFY school_id int NULL;
Insert records from the old tables into the new tables, making sure the values of
primary keys and foreign keys are stored in the target's corresponding old_xxxxxx columns.
In the example, it would look like this:
INSERT INTO School (old_id, name, address)
SELECT id, name, address
FROM oldSchool;
INSERT INTO Student (name, class, old_school_id)
SELECT name, class, school_id
FROM oldStudent;
Update the foreign key columns which are null by looking up the new id via the old_xxxx foreign key values. In our example:
UPDATE Student
SET school_id = (
SELECT id
FROM School
WHERE old_id = Student.old_id);
Now make those foreign key columns not nullable again:
ALTER TABLE Student MODIFY school_id int NOT NULL;
Enable the foreign key constraints again.
SET foreign_key_checks = 1;
Or if you had to drop them, recreate them, for example:
ALTER TABLE Student
ADD CONSTRAINT fk_school_id
FOREIGN KEY (school_id)
REFERENCES School(id);
Optionally drop all the old_xxxxx columns from all your tables. In the example:
ALTER TABLE Student DROP COLUMN old_school_id;
ALTER TABLE School DROP COLUMN old_id;
Optionally drop all old tables. In the example:
DROP TABLE oldStudent;
DROP TABLE oldSchool;
Done.

Delete query in sqlite for child tables

I have 3 tables, like Employee, Department and Electronics tables.
Electronics table is child table for Department table and Department table is child table for Employee table.
I want to delete one record in Employee table where E_id=2 ( this is Primary key) this is Foreign key in Department table (E_id is Foreign key and Dept_id is Primary key) and Dept_id is Foreign Key in Electronics table.
First I want to delete related records in Electronics table then Department table and finally Employee table.
Please guide me how to do it.
You can read more about foreign key support in sqlite here: http://www.sqlite.org/foreignkeys.html
but you should be able to turn it on:
sqlite> PRAGMA foreign_keys = ON;
and then setup the database schema with the deletes cascading:
-- Database schema
CREATE TABLE Employee(
E_id INTEGER PRIMARY KEY,
name TEXT
);
CREATE TABLE Department(
Dept_id INTEGER PRIMARY KEY,
name TEXT,
E_id INTEGER REFERENCES Employee(E_id) ON DELETE CASCADE
);
CREATE TABLE Electronics(
Elec_id INTEGER PRIMARY KEY,
name TEXT,
Dept_id INTEGER REFERENCES Department(Dept_id) ON DELETE CASCADE
);
With all this in place and the data in the tables:
DELETE FROM Employee WHERE E_id = 2;

Resources