Updating SQL Table In Enterprise Manager - Foreign Key Issues - sql

I have a table with a whole bunch of FKs.
Table Vehicles
-----------
ColorID -> Color.ID
MakeID -> Make.ID
ModelID -> Model.ID
etc...
My issue is that I forgot a few columns and I need to add them. I can add them through right clicking on the table and choosing 'Design', but not if I want to make them NOT NULL, or delete a column. I could also generate a Drop/Create Script, but I get this Error:
Msg 3726, Level 16, State 1, Line 4
Could not drop object 'dbo.SellVehicles' because it is referenced by a FOREIGN KEY constraint.
Do I need to go through and remove each FK and then drop/create, then add them back or is there a quick/painless way of doing this? Is there a way to drop and recreate these FKs quickly?
Why doesn't
IF EXISTS (SELECT * FROM sys.foreign_keys WHERE object_id = OBJECT_ID(N'[dbo].[FK_SellVehicles_Conditions]') AND parent_object_id = OBJECT_ID(N'[dbo].[SellVehicles]'))
ALTER TABLE [dbo].[SellVehicles] DROP CONSTRAINT [FK_SellVehicles_Conditions]
GO
eliminate this error? Is the FK still on the other table being referenced?

The constraint that is triggering the error is not on the dbo.SellVehicles table; it's on a table that references the dbo.SellVehicles table. The references to the Color, Make and Model tables aren't the issue--you're attempting to drop/delete the child in a parent-child relationship.
I doubt the constraint you test for existed prior to the ALTER TABLE ... DROP CONSTRAINT ....
In SSMS, you can right click on a table, and select "Dependencies". There's a radio button to select viewing the objects that depend on the dbo.SellVehicles table, or the stuff that the dbo.SellVehicles table depends on.

Related

Two FKs pointing to same parent column - ON UPDATE CASCADE - SQL Server

Here's the scenario.
- Parent Table: TEAMMEMBERS, with a primary key RecID
- Child Table: TEAMMEMBERTASKS
I have two columns in the TEAMMEMBERTASKS table, ReportedBy and AssignedTo.
Both of these columns use the RecID to store which team member reported a task and which team member the task is assigned to. The RecID could be the same for both columns, but that is not always the case.
I need to add in a FK for both child columns that check the relationship to the parent, and I would like to add ON UPDATE CASCADE to both of the foreign keys.
Whenever I try to do this, my second foreign key throws a 'may cause cycles or multiple cascade paths' error.
Here's my code:
ALTER TABLE [dbo].[TEAMMEMBERTASKS] WITH CHECK ADD CONSTRAINT
[FK_AssignedTo_TeamMemberRecID] FOREIGN KEY([AssignedTo])
REFERENCES [dbo].[TEAMMEMBERS] ([RecID])
GO
ALTER TABLE [dbo].[TEAMMEMBERTASKS] CHECK CONSTRAINT
[FK_AssignedTo_TeamMemberRecID]
GO
ALTER TABLE [dbo].[TEAMMEMBERTASKS] WITH CHECK ADD CONSTRAINT
[FK_ReportedBy_TeamMemberRecID] FOREIGN KEY([ReportedBy])
REFERENCES [dbo].[TEAMMEMBERS] ([RecID])
ON UPDATE CASCADE
GO
ALTER TABLE [dbo].[TEAMMEMBERTASKS] CHECK CONSTRAINT
[FK_ReportedBy_TeamMemberRecID]
GO
With the current code, will this cause the RecID to be updated in both child columns or will it cause the update command to be restricted?
Should I just go ahead and write up a trigger that deals with this instead?

How to delete records from parent table which is referenced by multiple child tables?

I have a table which is referenced by multiple tables (around 52) and further,few of the child tables have multiple foreign keys also that is referencing other tables too.
I want to delete a record from parent table, I am unable to do so, as I am getting error "The DELETE statement conflicted with the REFERENCE constraint "FK_xxx". The conflict occurred in database "MyDB", table "dbo.A", column 'x'."
I want a generalized T-SQL solution which is irrespective of tables and number of references.
You have to look at the "on delete" keyword which is a part of the foreign key constraint definition.
Basically you have 4 options:
NO ACTION (does nothing)
CASCADE (deletes the child aswell)
SET NULL (sets the reference field to null)
SET DEFAULT (sets the reference field to the default value)
An example would be:
CREATE TABLE parent (
id INT NOT NULL,
PRIMARY KEY (id)
) ENGINE=INNODB;
CREATE TABLE child (
id INT,
parent_id INT,
INDEX par_ind (parent_id),
FOREIGN KEY (parent_id)
REFERENCES parent(id)
ON DELETE CASCADE -- replace CASCADE with your choice
) ENGINE=INNODB;
(for this example and more details look here: http://dev.mysql.com/doc/refman/5.7/en/create-table-foreign-keys.html )
If you now want to modify your constraint, you first have to drop it, and create a new one like for example:
ALTER TABLE child
ADD CONSTRAINT fk_name
FOREIGN KEY (parent_id)
REFERENCES parent(id)
ON DELETE CASCADE; -- replace CASCADE with your choice
I hope this helped. Also to mention it, you should think about maybe not really deleting your parent, and instead creating another boolean column "deleted", which you fill with "yes" if someone clicks the delete. In the "Select"-query you filter then by that "deleted" column.
The advantage is, that you do not lose the history of this entry.
Your problem is this: A FK constraint is designed to prevent you from creating an orphaned child record in any of the 52 tables. I can provide you with the script you seek, but you must realise first that when you try to re-enable the FK constraints the constraints will fail to re-enable because of the orphaned data (which the FK constraints are designed to prevent). For your next step, will have to delete the orphaned data in each of the 52 tables first anyway. It is actually much easier just to redo the constraints with ON DELETE CASCADE, or drop the constraints and forget about referential integrity altogether. You can't have it both ways.

multiple cascade paths, on update cascade

I have a problem with sql server, when I want to have 3 table and make relationship between them, and change the "On Update" property to "cascade".
this problem happend when I want to save the diagram:
Introducing FOREIGN KEY constraint 'FK_Company_Slave' on table 'Company' may cause cycles or multiple cascade paths. Specify ON DELETE NO ACTION or ON UPDATE NO ACTION, or modify other FOREIGN KEY constraints.
Could not create constraint. See previous errors.
in this picture, I define my data base, FK and ....
thanks.
First:
A FOREIGN KEY in one table points to a PRIMARY KEY in another table. if you don't want to use PRIMARY KEY on other table in order to foreign key, you must be create unique index on the table.
Second:
you can create after trigger on Master table in order to develop on update cascade manually. In other word your foreign key between Company table and Master table created without on update cascade and then create following trigger on master to update company table after changed row in Master table.
create trigger triggername on dbo.[Master]
After Insert
AS Begin
Update Company
Set MasterKey = I.MasterKey
From Inserted I
Inner join Deleted D on D.Code = I.Code
Where Company.MasterKey = D.MasterKey
End

What can I do about a SQL Server ghost FK constraint?

I'm having some trouble with a SQL Server 2005 database that seems like it's keeping a ghost constraint around. I've got a script that drops the constraint in question, does some work, and then re-adds the same constraint. Normally, it works fine. Now, however, it can't re-add the constraint because the database says that it already exists, even though the drop worked fine!
Here are the queries I'm working with:
alter table individual drop constraint INDIVIDUAL_EMP_FK
ALTER TABLE INDIVIDUAL
ADD CONSTRAINT INDIVIDUAL_EMP_FK
FOREIGN KEY (EMPLOYEE_ID)
REFERENCES EMPLOYEE
After the constraint is dropped, I've made sure that the object really is gone by using the following queries:
select object_id('INDIVIDUAL_EMP_FK')
select * from sys.foreign_keys where name like 'individual%'
Both return no results (or null), but when I try to add the query again, I get:
The ALTER TABLE statement conflicted with the FOREIGN KEY constraint "INDIVIDUAL_EMP_FK".
Trying to drop it gets me a message that it doesn't exist. Any ideas?
It means the data is wrong on creation of the FK
That is, you have "EMPLOYEE_ID" values in the INDIVIDUAL child table that don not exist in the parent EMPLOYEE table.
You could use ALTER TABLE ...WITH NOCHECK ADD CONSTRAINT... but then the FK is no use

Create a one to many relationship using SQL Server

How do you create a one to many relationship using SQL Server?
Define two tables (example A and B), with their own primary key
Define a column in Table A as having a Foreign key relationship based on the primary key of Table B
This means that Table A can have one or more records relating to a single record in Table B.
If you already have the tables in place, use the ALTER TABLE statement to create the foreign key constraint:
ALTER TABLE A ADD CONSTRAINT fk_b FOREIGN KEY (b_id) references b(id)
fk_b: Name of the foreign key constraint, must be unique to the database
b_id: Name of column in Table A you are creating the foreign key relationship on
b: Name of table, in this case b
id: Name of column in Table B
This is a simple example of a classic Order example. Each Customer can have multiple Orders, and each Order can consist of multiple OrderLines.
You create a relation by adding a foreign key column. Each Order record has a CustomerID in it, that points to the ID of the Customer. Similarly, each OrderLine has an OrderID value. This is how the database diagram looks:
In this diagram, there are actual foreign key constraints. They are optional, but they ensure integrity of your data. Also, they make the structure of your database clearer to anyone using it.
I assume you know how to create the tables themselves. Then you just need to define the relationships between them. You can of course define constraints in T-SQL (as posted by several people), but they're also easily added using the designer. Using SQL Management Studio, you can right-click the Order table, click Design (I think it may be called Edit under 2005). Then anywhere in the window that opens right-click and select Relationships.
You will get another dialog, on the right there should be a grid view. One of the first lines reads "Tables and Columns Specification". Click that line, then click again on the little [...] button that appears on the right. You will get this dialog:
The Order table should already be selected on the right. Select the Customer table on the left dropdown. Then in the left grid, select the ID column. In the right grid, select the CustomerID column. Close the dialog, and the next. Press Ctrl+S to save.
Having this constraint will ensure that no Order records can exist without an accompanying Customer record.
To effectively query a database like this, you might want to read up on JOINs.
This is how I usually do it (sql server).
Create Table Master (
MasterID int identity(1,1) primary key,
Stuff varchar(10)
)
GO
Create Table Detail (
DetailID int identity(1,1) primary key,
MasterID int references Master, --use 'references'
Stuff varchar(10))
GO
Insert into Master values('value')
--(1 row(s) affected)
GO
Insert into Detail values (1, 'Value1') -- Works
--(1 row(s) affected)
insert into Detail values (2, 'Value2') -- Fails
--Msg 547, Level 16, State 0, Line 2
--The INSERT statement conflicted with the FOREIGN KEY constraint "FK__Detail__MasterID__0C70CFB4".
--The conflict occurred in database "Play", table "dbo.Master", column 'MasterID'.
--The statement has been terminated.
As you can see the second insert into the detail fails because of the foreign key.
Here's a good weblink that shows various syntax for defining FK during table creation or after.
http://www.1keydata.com/sql/sql-foreign-key.html
If you are not using SSMS then here is the syntax:
ALTER TABLE <table_name>
ADD <constraint_name> FOREIGN KEY
(<column_name1> ,
<column_name2> )
REFERENCES <table_name>
(<column_name1> ,
<column_name2>)
http://infogoal.com/sql/sql-add-foreignkey.htm
If you are talking about two kinds of enitities, say teachers and students, you would create two tables for each and a third one to store the relationship. This third table can have two columns, say teacherID and StudentId.
If this is not what you are looking for, please elaborate your question.