Cascade tree deleting in MS SQL Server Express 2005 - sql-server

One table has the name "Stages", every Stage can have 0 to infinity children. In the table "Stages" there is a column named "Parent". This column is foreign a key for the same table "Stages".
How would I make a cascading delete for this tree? I want to when deleting any row in this table, automatically delete all their children and their children's children...
With the following query
GO
IF NOT EXISTS (SELECT * FROM sys.foreign_keys WHERE object_id = OBJECT_ID(N'[dbo].[FK_Stage_Stage]') AND parent_object_id = OBJECT_ID(N'[dbo].[Stage]'))
ALTER TABLE [dbo].[Stage] WITH CHECK ADD CONSTRAINT [FK_Stage_Stage] FOREIGN KEY([parent])
REFERENCES [dbo].[Stage] ([id]) ON DELETE CASCADE
GO
ALTER TABLE [dbo].[Stage] CHECK CONSTRAINT [FK_Stage_Stage]
GO
I get this error
Msg 1785, Level 16, State 0, Line 2
Introducing FOREIGN KEY constraint 'FK_Stage_Stage' on table 'Stage' may cause cycles or multiple cascade paths. Specify ON DELETE NO ACTION or ON UPDATE NO ACTION, or modify other FOREIGN KEY constraints.
Msg 1750, Level 16, State 0, Line 2
Could not create constraint. See previous errors.
Msg 4917, Level 16, State 0, Line 1
Constraint 'FK_Stage_Stage' does not exist.
Msg 4916, Level 16, State 0, Line 1
Could not enable or disable the constraint. See previous errors.

Add foreigns key with ON DELETE CASCADE option for all "child" tables.
ALTER TABLE SomeChildTable
CONSTRAINT YOurConstraintName
FOREIGN KEY (YourParentId)
REFERENCES YourParentTable(ParentTableId) ON DELETE CASCADE;
for new tables:
CREATE TABLE ttt
(
...
CONSTRAINT YOurConstraintName
FOREIGN KEY (YourParentId)
REFERENCES YourParentTable(ParentTableId) ON DELETE CASCADE
)

Related

How to delete a column which is the primary key in SQL Server

I'm getting an error while trying to delete the primary key column from the table.
id - primary key column
Table OLTMS_0B8DF2
Query
ALTER TABLE OLTMS_0B8DF2
DROP CONSTRAINT id;
GO
Error
Msg 3728, Level 16, State 1, Line 1
'id' is not a constraint.
Msg 3727, Level 16, State 0, Line 1
Could not drop constraint. See previous errors.
You need to specify the existing constraint name rather than the column name to drop the constraint.
You can determine the PK constraint name using the SSMS object browser or with the T-SQL script below. A best practice is to explicitly name constraints (e.g. PK_OLTMS_0B8DF2) rather than rely on auto-generated constraint names. That makes subsequent DDL easier.
SELECT name
FROM sys.key_constraints AS pk
WHERE
pk.parent_object_id = OBJECT_ID(N'OLTMS_0B8DF2')
AND type = 'PK';
If you have foreign key constraints referencing the table, you'll need to similarly drop those too.

Deleted Foreign Key Constraint causing error

I'm trying to create a FK constraint by using this auto created script.
USE [PRM.Mobile.SaaS]
GO
ALTER TABLE [dbo].[Activity] WITH CHECK
ADD CONSTRAINT [FK_Activity_Activity]
FOREIGN KEY([ParentActivityID]) REFERENCES [dbo].[Activity] ([ActivityID])
GO
ALTER TABLE [dbo].[Activity] CHECK CONSTRAINT [FK_Activity_Activity]
GO
But I get these errors:
Msg 547, Level 16, State 0, Line 4
The ALTER TABLE statement conflicted with the FOREIGN KEY SAME TABLE constraint "FK_Activity_Activity". The conflict occurred in database "PRM.Mobile.SaaS", table "dbo.Activity", column 'ActivityID'.
Msg 4917, Level 16, State 0, Line 8
Constraint 'FK_Activity_Activity' does not exist.
Msg 4916, Level 16, State 0, Line 8
Could not enable or disable the constraint. See previous errors.
Looks pretty straightforward but I don't have any FK with a name of FK_Activity_Activity anymore. Also first message being a FK constraint preventing the action and second message being that constraint is not existing is a bit confusing.
I double checked the INFORMATION.SCHEMA and sys.objects and nothing with a name of FK_Activity_Activity shows up.
These are the queries I used for checking
SELECT *
FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS
WHERE CONSTRAINT_NAME LIKE '%Activity_Activity%'
and
SELECT
OBJECT_NAME(object_id) AS ConstraintName,
SCHEMA_NAME(schema_id) AS SchemaName,
type_desc AS ConstraintType
FROM
sys.objects
WHERE
type_desc LIKE '%CONSTRAINT'
AND OBJECT_NAME(parent_object_id) = 'Activity'
What am I missing here?
The add constraint failed with the first error: the FK is not created.
The second error is from the second statement because the FK does not exist.
Everything else follows from there.
R TABLE [dbo].[Activity] WITH CHECK
ADD CONSTRAINT [FK_Activity_Activity]
FOREIGN KEY([ParentActivityID]) REFERENCES [dbo].[Activity] ([ActivityID])
To fix things so you can create the index you need to correct your data so it is consistent with the new FK before you create the index. Whether than is modifying the data in ParentActivityID or ActivityID only you can say.
But note any recursive structure needs to allow for ParentActivityID being null (unless the graph is specifically cyclic). Usually this is by making it null.

Column is not the same data type as referencing column

I'm altering table to add a foreign key as following:
ALTER TABLE [MS_Test].[dbo].[Studies]
ADD CONSTRAINT F_Id
FOREIGN KEY (Id) REFERENCES [M_Test].[dbo].[MS](Id);
I get the following error:
Msg 1778, Level 16, State 0, Line 2
Column 'MS_Test.dbo.FM.Id' is not the same data type as referencing column 'Studies.Id' in foreign key 'F_Id'.
Msg 1750, Level 16, State 0, Line 2
Could not create constraint or index. See previous errors.
I have already a lot of data stored in my tables so I can't just drop table and create it again.
SQL has the following command:
ALTER TABLE [table] ALTER COLUMN [column] SET DATA TYPE [new data type]
EDIT
As you modified the question, it seems that you need to add a new column, instead of changing an existing one.
Try something like this:
ALTER TABLE [MS_Test].[dbo].[Studies]
ADD COLUMN MS_id {your [MS_Test].[dbo].[MS].Id column type};
ALTER TABLE [MS_Test].[dbo].[Studies]
ADD CONSTRAINT F_Id
FOREIGN KEY (MS_id) REFERENCES [M_Test].[dbo].[MS](Id);

sql - update two key columns without conflict

I want to to update a column from table patient, and add a prefix before all its fields, like
update patient
set contactdetailsID = '99999'+ contactdetailsID
where patient.id = 5294
So, row with id = 5294, will have the same value in column contactdetailsID with prefix 99999.
Before | After
012345 99999012345
the issue i am facing is that patient.contactdetailsID is the foreign key for another table "contactdetails".
So i get the following error.
Msg 547, Level 16, State 0, Line 1 UPDATE statement conflicted with
COLUMN FOREIGN KEY constraint 'ContactDetails_Patient_FK1'. The
conflict occurred in database 'A', table 'ContactDetails',
column 'id'. The statement has been terminated.
(0 row(s) affected)
How can i make that change? I want to change both patient.contactdetailsID and its key Contactdetails.ID, with the same prefix in order not to lose the connection between them.
You can temporary disable the Foreign-Key Constraint using:
ALTER TABLE *Tablename*
NOCHECK CONSTRAINT *ForeinKey_Name*;
and update both the ContactDetails Table and Patient Table.
But make sure that you enable the ForeignKey afterwards!
To enable a Foreign Key use
ALTER TABLE *Tablename*
CHECK CONSTRAINT *ForeinKey_Name*;
You could implement ON UPDATE CASCADE in your table.
see MySQL documentation

Getting error on create table with foreign key constraint (Cascade)

create table employee
(
eid int primary key,
ename varchar(50),
cid int,
sid int,
constraint fk_hello1 foreign key(cid) references country(cid)on delete
cascade on update cascade,
constraint fk_hello2 foreign key(sid) references state(sid) on delete
cascade on update cascade,
)
I have been trying to apply this code but am constantly getting the error msg.........
ERROR MESSAGE
Msg 1785, Level 16, State 0, Line 1
Introducing FOREIGN KEY constraint 'fk_hello2' on table 'employee' may
cause cycles or multiple cascade paths. Specify ON DELETE NO ACTION or
ON UPDATE NO ACTION, or modify other FOREIGN KEY constraints.
Msg 1750, Level 16, State 0, Line 1
Could not create constraint. See previous errors.
You can not use on update cascade when you have cycle references in you relations in database structure:
Only NO ACTION allowed (see you error Specify ON DELETE NO ACTION or
ON UPDATE NO ACTION)
Is State from country has a different meaning then state in employee ?
Correct solution:
and table [Employee] must have one foreign key on multiple columns - FK(CID, SID)

Resources