SQL Server 2008 - deleting rows with FK constraints - sql

I've got SQL database in SQL Server 2008 generated as follows:
CREATE TABLE Client (
ID bigint,
Code varchar(50),
ClientID int NOT NULL
);
ALTER TABLE Client
ADD CONSTRAINT PK_Client PRIMARY KEY CLUSTERED (ClientID);
CREATE TABLE Company (
ID bigint,
Description nvarchar(100),
SubsidiaryOf bigint,
companyID int NOT NULL,
FK_Client_Company int,
PK_Company int
);
ALTER TABLE Company
ADD CONSTRAINT PK_Company PRIMARY KEY CLUSTERED (companyID);
ALTER TABLE Company
ADD CONSTRAINT (ID = ID) FOREIGN KEY (FK_Client_Company)
REFERENCES Client (ClientID);
ALTER TABLE Company
ADD CONSTRAINT (SubsidiaryOf = ID) FOREIGN KEY (PK_Company)
REFERENCES Company (companyID);
CREATE TABLE ContactData (
ID bigint,
LocationID bigint,
Contact nvarchar(50),
contactDataID int NOT NULL,
PK_Location int
);
ALTER TABLE ContactData
ADD CONSTRAINT PK_ContactData PRIMARY KEY CLUSTERED (contactDataID);
ALTER TABLE ContactData
ADD CONSTRAINT (LocationID = ID) FOREIGN KEY (PK_Location)
REFERENCES Location (locationID);
CREATE TABLE Location (
ID bigint,
CompanyID bigint,
Country nvarchar(50),
ZIPCode nvarchar(50),
locationID int NOT NULL,
PK_Company int
);
ALTER TABLE Location
ADD CONSTRAINT PK_Location PRIMARY KEY CLUSTERED (locationID);
ALTER TABLE Location
ADD CONSTRAINT (CompanyID = ID) FOREIGN KEY (PK_Company)
REFERENCES Company (companyID);
And would like to delete all the Companies with ID > 140000 (with related rows in other tables). I tried some combination of INNER JOINs all together in one transaction, but there is still a problem with FK_Client_Company constraint. Can anyone help me?
One more thing - I cannot add anything/modify DB structure/constraints. It has to be a query-base-solution.

First delete those companies' clients
delete client where id in (select fk_client_company from company where id > 140000)
After that you should be able to run the delete statement on the company table
delete company where id > 140000
I'm 'fairly' sure that's the answer you're looking for but I'm not a 100% positive only because your naming scheme seems a little odd. I'm making the assumption that company.fk_client_company = client.id.

Related

How to index a SQL table on a column in another table

I have the schema below - Let's pretend that there are 2 countries, A and B.
Country A has 1000 teams whereas country B has 100,000,000 - If I want to quickly query results based off which country the team is in, how would I construct my index?
Teams cannot change country if that helps.
Indexing a table depend upon knowing real schema.
For this simple table schema, I will create only Trusted FK between tables, at least this will be my first try.
Assuming Countryid,Teamid,Resultid are auto increment.
CREATE TABLE Country
(
id INT IDENTITY(1, 1) PRIMARY KEY,
CountryName VARCHAR(100) NOT NULL
);
CREATE TABLE Team
(
id INT IDENTITY(1, 1) PRIMARY KEY,
TeamName VARCHAR(100) NOT NULL,
CountryID INT NOT NULL
);
ALTER TABLE dbo.Team WITH CHECK
ADD CONSTRAINT FK_Team_CountryID
FOREIGN KEY(CountryID) REFERENCES dbo.Country(id);
ALTER TABLE dbo.Team WITH CHECK
CHECK CONSTRAINT FK_Team_CountryID;
--Just verify that newly created FK is trusted or not.
SELECT
name,
is_disabled,
is_not_trusted
FROM
sys.foreign_keys
WHERE
name = 'FK_Team_CountryID';
CREATE TABLE Result
(
id INT IDENTITY(1, 1) PRIMARY KEY,
TeamId INT NOT NULL,
Result INT NOT NULL
);
-- I have no idea how you are storing Result,so ignore it
ALTER TABLE dbo.Result WITH CHECK
ADD CONSTRAINT FK_Result_TeamId
FOREIGN KEY(TeamId) REFERENCES dbo.Team(id);
ALTER TABLE dbo.Result WITH CHECK
CHECK CONSTRAINT FK_Result_TeamId;
May be after seeing query plan of real query, I will De-normalise Result table to add Countryid , but for now it is not require since country table will be small

Issues with creating SQL Server table relationships

I have 2 tables.
First table:
create table abc
(
AId INT IDENTITY(1,1),
Name NVARCHAR(50),
EMP NVARCHAR(50)
CONSTRAINT PK_abc PRIMARY KEY (AId, Name)
)
And second table as:
create table def
(
AId INT,
Comment NVARCHAR(50)
constraint FK_aid FOREIGN KEY (AId) references abc (AId)
)
This throws an error:
There are no primary or candidate keys in the referenced table 'abc' that match the referencing column list in the foreign key 'FK_aid'.
So I updated as:
create table def
(
AId INT,
Name NVARCHAR(50),
Comment NVARCHAR(50)
constraint FK_AID FOREIGN KEY (AId, Name) references abc (AId, Name)
)
But this throws another error:
More than one key specified in column level FOREIGN KEY constraint, table 'def'.
Not sure what am I missing here.
---Updated----
Sorry for giving vague example. I was having difficulty in explaining my problem here. I have attached the screenshot of my problem. This show the eventual output that I am expecting by making join to 3 tables. Where the data of 3 tables is populated from an input form.
I have tried to provide in a clear way. Let me know if you need more inputs.
Attchment at:
https://imgur.com/a/jfFS6
Thanks
You have an identity column. Use it as the primary key:
create table abc (
AId INT IDENTITY(1,1) PRIMARY KEY,
Name NVARCHAR(50),
EMP NVARCHAR(50)
);
create table def (
AId INT,
Comment NVARCHAR(50)
constraint FK_aid FOREIGN KEY (AId) references abc (AId)
);
Name should not be in the definition of the primary key.
Looks like you have to do it as a separate statement:
ALTER TABLE [dbo].[def] WITH CHECK ADD CONSTRAINT [FK_def_abc] FOREIGN KEY([AId], [Name])
REFERENCES [dbo].[abc] ([AId], [Name])
GO
ALTER TABLE [dbo].[def] CHECK CONSTRAINT [FK_def_abc]
GO
But you still should NOT do that. Identity is unique and it alone should be used as primary key.

Foreign key in the first table

I have a question about foreign keys.
How does it work when I want to add a foreign key to the first table that I make that references to the primary key of the second table I create?
CREATE TABLE table1
(
name_id INT NOT NULL,
team TEXT REFERENCES table2(team_id),
PRIMARY KEY(name_id)
);
CREATE TABLE table2
(
team_id INT NOT NULL,
teamname TEXT,
PRIMARY KEY(team_id)
);
If I try the code above I get the following error:
ERROR: relation "" does not exist
Thanks in advance.
Either create the second table first. Or use alter table. That is, create the first table without the reference and then do:
alter table table1 add constraint fk_table1_team
foreign key (team_id) REFERENCES table2(team_id);
The declaration for table1 would be:
CREATE TABLE table1 (
name_id INT NOT NULL,
team_id INT,
PRIMARY KEY(name_id)
);
The reference between the tables should be on the primary key and certainly not on a character column, if an integer is available.
here's the syntax of creating a table with Foreign key:
CREATE TABLE table11
(
name_id INT NOT NULL,
team INT,
PRIMARY KEY(name_id),
foreign key(team) references table22(team_id)
);
CREATE TABLE table22
(
team_id INT NOT NULL,
teamname TEXT,
PRIMARY KEY(team_id)
);
but there was another problem. a foreign key from a child table cannot reference to a primary key from a parent folder if they do not contain the same type. in your code team was of TEXT and team_id was of INT which cannot be.

how to delete relationship between two tables?

I created two tables How to delete relationship between them in sql code;
Course table:
create table course
(
course_id int primary key identity (1,1),
course_name varchar(40)
);
Employee table:
create table employee
(
emp_id int identity(1,1) primary key,
fname varchar(30),
course_id int
foreign key references course (course_id)
);
If this is for SQL Server - then you can find out the name of the FK constraint using this statement:
SELECT name
FROM sys.foreign_keys
WHERE parent_object_id = OBJECT_ID('employee')
AND referenced_object_id = OBJECT_ID('course')
and once you have that FK constraint name, you can use the usual
ALTER TABLE dbo.employee DROP CONSTRAINT (name of the FK constraint)
This will be an arbitrary, system-generated name (something like FK__employee__cours__7EB7AD3A or similar) - and this is the reason I'd recommend to always explicitly name your constraints - like this:
create table employee
(
emp_id int identity(1,1) primary key,
fname varchar(30),
course_id int
constraint fk_employee_course
foreign key references course (course_id)
);
Now, you know what the name of that FK constraint is - you named it fk_employee_course. This is also beneficial if you get any error messages about FK constraint violations - if that name is intuitive and obvious, then you'll know what went wrong

How to link tables in SQL

I have two tables and i want to create a third that references the other two.
stock_group has groupno as primary key
stock_group2s also has groupno as primary key
I want to create table called stock_group3s, with 5 columns:
key int AUTO INCREMENT PRIMARY KEY
groupno INT
group1 [stock_group.groupno]
group2 [stock_group2s.groupno]
name VARCHAR (30)
The two linked columns then must contain only a value that can be found in their referenced tables.
How do set this up? I am using SQL Server 2008 R2 with SQL Server 2008 Management Studio
perhaps you are looking for
create table stock_group (groupno int primary key)
create table stock_group2s(groupno int primary key)
create table stock_group3s
(
IDkey int PRIMARY KEY IDENTITY(1,1)
,groupno INT
,group1 INT
,group2 INT
,name VARCHAR (30)
)
ALTER TABLE stock_group3s WITH NOCHECK ADD CONSTRAINT FK_stock_group3s_stock_group FOREIGN KEY(group1)
REFERENCES stock_group (groupno)
ALTER TABLE stock_group3s WITH NOCHECK ADD CONSTRAINT FK_stock_group3s_stock_group2s FOREIGN KEY(group2)
REFERENCES stock_group2s (groupno)