Deleted Foreign Key Constraint causing error - sql-server

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.

Related

Keep getting incorrect syntax near keyword CONSTRAINT in ALTER TABLE when trying to create foreign keys for a table?

I am currently I am working in sql server and have the following code. I am trying to create two foreign keys under the 'ASSIGNMENT' table, as well as create a primary key for the 'ASSIGNMENT' table. However, I keep running into problems when trying to execute my codes for creating the foreign keys and when trying to create the primary key.
For the foreign keys, my code is:
ALTER TABLE dbo.ASSIGNMENT ALTER COLUMN ProjectID INTEGER;
ADD CONSTRAINT PROJECT_FK FOREIGN KEY (ProjectID) REFERENCES dbo.
PROJECT (ProjectID);
ALTER TABLE dbo.ASSIGNMENT ALTER COLUMN EmployeeNumber CHAR(25);
ADD CONSTRAINT EMPLOYEE_FK FOREIGN KEY (EmployeeNumber) REFERENCES
dbo.EMPLOYEE (EmployeeNumber);
The message that pops up is:
Msg 156, Level 15, State 1, Line 2
Incorrect syntax near the keyword 'CONSTRAINT'.
Msg 156, Level 15, State 1, Line 5
Incorrect syntax near the keyword 'CONSTRAINT'.
My instructor wants us to use ALTER table in order to create the foreign keys, but I am unsure how to create them for the assignment table specifically. I have been able to create foreign keys for employee and project tables under their respective tables, but am unsure how to create them for this specific table.
For trying to create the primary key, I was not given a primary key and am unsure how to proceed. My code thus far is:
ALTER TABLE dbo.ASSIGNMENT ADD CONSTRAINT ASSIGNMENT_PK PRIMARY KEY
(ID);
The error message that pops up is:
Msg 1911, Level 16, State 1, Line 1
Column name 'ID' does not exist in the target table or view.
Msg 1750, Level 16, State 0, Line 1
Could not create constraint or index. See previous errors.
I am unsure how to create a primary key for this 'ASSIGNMENT' table because within the ERD provided by the instructor, there are 3 columns for ProjectID, EmployeeNumber, and Hours Worked. The first two are also foreign keys, but there is no explicit assignment pk given. Thus, I am unsure how to create a primary key for this table, and what the command would be under the ALTER table, as instructed by my instructor.
Any help understanding where I am going wrong on any of my codes, and guidance would be greatly appreciated! Thanks!
You cannot have ADD and also ALTER keywords in an ALTER TABLE !
The right syntax to add a constraint is :
ALTER TABLE dbo.ASSIGNMENT
ADD CONSTRAINT EMPLOYEE_FK
FOREIGN KEY (EmployeeNumber)
REFERENCES dbo.EMPLOYEE (EmployeeNumber);
This came from SQL ISO Standard SQL...

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.

Error while adding a foreign key constraint

Msg 547, Level 16, State 0, Line 2
The ALTER TABLE statement conflicted with the FOREIGN KEY constraint
"AB_TRANS_FK3". The conflict occurred in database "DEV", table
"dbo.PRODUCT", column 'ID'.
Hello all,
I need your help with this error. I am trying to add a foreign key constraint here using the following query
ALTER TABLE [dbo].[AB_TRANS] WITH CHECK ADD CONSTRAINT [AB_TRANS_FK3] FOREIGN KEY([ID])
REFERENCES [dbo].[PRODUCT] ([ID])
Check your table to see which row(s) are causing the issue, then you'll need to fix them. This should help:
SELECT *
FROM
dbo.AB_Trans A
WHERE
NOT EXISTS (SELECT * FROM dbo.Product P WHERE P.ID = A.ID)
If there isn't a match, are you using "0" for the ID or some other dummy value? This could certainly cause the problem as you should be using NULL in those cases.

Unable to get a Foreign key

USE Kudler_FF
ALTER TABLE Employee_Tbl
ADD CONSTRAINT FK_Employee_Tbl
FOREIGN KEY (JobTitle) REFERENCES Job_Tbl (JobTitle);
Message I am getting:
Msg 547, Level 16, State 0, Line 2
The ALTER TABLE statement conflicted with the FOREIGN KEY constraint "FK_Employee_Tbl". The
conflict occurred in database "Kudler_FF", table "dbo.Job_Tbl", column
'JobTitle'.
What did I add or not add
You usually only get an error adding a foreign key constraint when the constraint would be violated by the current data.
In other words, you probably have a value in Employee_Tbl(JobTitle) that does not exist in Job_Tbl(JobTitle).
You would not be able to add such a constraint until your data is modified so that a violation would not occur.
Find the values for JobTitle in Employee_Tbl that don't exist in Job_Tbl and then add them to that latter table.
I'm not sure of the exact syntax for SQL Server but you could start with:
select distinct JobTitle from Employee_Tbl
where JobTitle not in (
select distinct JobTitle from Job_Tbl
)

Cascade tree deleting in MS SQL Server Express 2005

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
)

Resources