Delete from multiple tables SQL - sql-server

I trying to figure out how I can delete from multiple tables in SQL Server.
I have one table containing only one primary key and three foreign keys for the three table I want to delete from. The other three table does not contain any foreign keys.
The stored procedure have one parameter, a specific primary key from one of the tables. I want to delete from the other tables WHERE tableID = #tableID. The constraints between the tables are set to cascade.
Is it possible with only that parameter to delete from all four tables?
I've tried with inner join, outer join, temptable..
Table Table Table Table
Pk Pk(Fk1) Pk(Fk2) Pk(Fk3)
Fk1 Column Column Column
Fk2 Column Column Column
Fk3
I have the table 2 Pk as parameter.

if your foreign keys were created with DELETE CASCADE, once you delete from the main table, all the related rows on the foreign tables will be delete too.
It seems like this is how it is configured, isnt it working?

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.

Rename table in Sql Server and updating references

Hi I need to rename a table, and add some columns to it.
This table has a PK column (Id) and a Self-referencing column (ParentId). These constraints use the old table name in their names.
There are also other tables that use this tables PK as foreign keys.
So, what would be the correct way to do this, asssuming that I need to rename TableA->TableB?
Drop constraints in all tables that reference TableA.Id
sp_rename 'dbo.TableA', 'TableB'
Add constraints that were dropped with new names?
Or, there is some other way?

Create script for deleting tables with foreign keys in order

I need to create a script (SQL Server 2012) that deletes tables from one specific schema, I'm not using cascade delete. I'm for example getting all the tables from sys.tables for that specific schema. Is there any way of getting the tables in order that I delete first the ones with FK and after the main ones? like cascade delete but in a script. I know I can use "nocheck constraint all" but I prefer to do it directly.
Thank you.
Not possible sadly.
You can have a loop of FKs so that no sequence of deletes will work.
The simplest is a pair of tables where each references the other.
-- Pathological foreign keys
-- There is no order in which you can drop these tables
CREATE TABLE one(a INT PRIMARY KEY, b INT)
CREATE TABLE two(a INT PRIMARY KEY, b INT)
ALTER TABLE one ADD FOREIGN KEY (b) REFERENCES two(a)
ALTER TABLE two ADD FOREIGN KEY (b) REFERENCES one(a)

How to delete record in Parent table without affecting the Child table?

I have 2 tables in my database, Table A and Table B.
Table A is a Master table and table B is a Transaction table. Table B have Foreign Key (IdTableA)
Example :
I already have a record in table B with IdTableA in it.
INSERT INTO Table_B VALUES (IdTableB, IdTableA, 500000);
and when I tried to delete record in Table A which is IdTableA there is an error.
I want to delete a record in Table A without affecting record in Table B
what should i do ? is it possible ?
You didn't post the error message, but most likely the IdTableA column is a foreign key to Table A. That means a row in Table A can't be deleted if any row in Table B references that row. There is no way to get around this except to permanently remove the foreign key.
The purpose of a foreign key is to prevent exactly this scenario. It prevents data integrity problems where rows would otherwise make no logical sense because other rows they reference do not actually exist.
http://en.wikipedia.org/wiki/Foreign_key

No foreign key restraints on a temporary table? SQL Server 2008

I know that a a temporary table will only exist for as long as a session of SQL Server is open, but why can't you have foreign key restraints on them?
Imagine this scenario: You create a foreign key relationship from your temp table to a concrete table's key. One of the restrictions on a foreign key relationship is that you cannot delete a row from a key table that is depended upon by your temp table. Now, generally when you create foreign key relationships you know to delete the dependent table rows before deleting the related rows in the key table, but how does a stored procedure or any other call into the database know to delete rows from your temp table? Not only is it impossible to discover spurious foreign key dependencies, other sessions could not reach your temp table even if it could discover the relationship. This leads to spurious failures in delete statements as foreign key constraints restrict the key table for dependent rows.
You can create foreign keys between tables in tempdb. For example, try this:
use tempdb
create table parent
(
parent_key int primary key clustered
)
create table child
(
child_key int primary key clustered,
child_parent_key int
)
alter table child add constraint fk_child_parent foreign key (child_parent_key) references parent(parent_key)
insert into parent(parent_key) select 1
insert into child(child_key, child_parent_key) select 1, 1
insert into child(child_key, child_parent_key) select 2, 2 -- this fails because of the FK constraint
drop table child
drop table parent
Could be because you can't have cross-database foreign key constraints and temp tables technically are created in the TempDB database.
Unless you mean between a temp table and another temp table... but really there's lots of issues you get into when you talk about those kind of constraints on a temp table.

Resources