Foreign Keys left after table deletion? - sql

So here's an interesting one for you... I am working on copying one entire database (db1) and structure over from one database to another (db2), and before doing so I decided to try and drop all tables from the db2. I did the usual sp_msforeachtable 'ALTER TABLE ? NOCHECK CONSTRAING ALL' and then sp_msforeachtable 'DROP TABLE ?' and much to my dismay, it deleted all save for maybe 6 tables. These tables seemed to still have foreign key references to them. I did a search and found this SQL DROP TABLE foreign key constraint which showed me how to find and then try to delete those foreign key references.
This is the interesting part: upon attempting to delete them using that information, I have been told that ssms cannot find the object because it does not exist or I do not have permission. The foreign key reference is coming from a table that I have previously deleted.
How is that possible? And how on earth do I progress from here?

I don't know what you mean by them in "upon attempting to delete them". If you were trying to delete the foreign key from the system tables, that would definitely be a mistake.
My guess is you can just drop those last 6 tables now.
Suppose we have two tables A and B
create table A (a int)
create table B(b int, foreign key (b) references (A.a))
and we try to drop the tables. drop table A will fail, because B references it with a declared foreign key. But we can freely drop table B, because A doesn't care if it's no longer being referenced.
So after the first pass, one DROP failed and one succeeded, leaving one table, now with no FK references. Try again and, voila!, drop table A now works.

Related

drop all constraints in a postgresql table - drop cascade

I have 21 tables in my database. However, there are some issues with the table schema (as we are trying to improve our data model). I already referred this post but it is for SQL server.
Currently, just for validation purpose, I would like to upload data inside them.
However, some ill-defined constraints are causing trouble.
So, I would like to delete all constraints only (from all tables) like Foreign key, check , unique, PK, Index etc.
How can I do this?
Currently I tried the below
ALTER TABLE subject
DROP CONSTRAINT subject_details_pk CASCADE;
ALTER TABLE subject
DROP CONSTRAINT subject_foreign_fk CASCADE;
As you can see, I have to write line by line across different tables (and manually find out which table is parent and which table is child etc).
So, is there any other way to drop all constraints in a table? Like Drop cascade ?
Can help me with this?

Adding foreign key fails unless data is first removed and reinserted after

I have an odd issue with foreign keys. I am trying to perform the following query:
ALTER TABLE [GroupMember] FOREIGN KEY ([Group]) REFERENCES [Group]([GUID])
Which gives me the following error:
The ALTER TABLE statement conflicted with the FOREIGN KEY constraint "FK__GroupMember__Group__0D25C822". The conflict occurred in database "x", table "dbo.Group", column 'GUID'.
I then verified the existing things, which I have confirmed are all ok:
Referenced table (dbo.Group) has a defined PRIMARY KEY on [GUID] column
Referencing table (dbo.GroupMember) has no [Group]-values which do not exist in [GUID]-column of dbo.Group-table
No similarly referencing foreign keys exist already
From here on, I experimented. Taking some rows in and out, wiping the table, truncating the table. What I can conclude so far:
If I wipe the referencing table using DELETE FROM [GroupMember]; then try to apply the FK constraint, I receive the same error message
If I truncate the referencing table using TRUNCATE TABLE [GroupMember];, I can apply the FK constraint without errors. Additionally, I am able to reinsert the exact same data after applying the FK constraint, without problems.
From this I can conclude that the data itself is not the problem. Can anyone make sense of this? Why am I able to apply the constraint after truncating the table, but not after deleting all records?
If you are using Microsoft SSMS check whether unchecking "Prevent saving changes that require table re-creation" solves the problem. You'll find this in Options > Designers > Table and Database Designers.
I have had similar issues that have been resolved by this. Let me know if it works or not.
Good luck.

TRUNCATE TABLE query unable to execute in SSIS because of foreign key

I have a table Person which contains 2 fields.In my another database i have a Participant Table(also have 2 columns).From Participant Table i have to insert values into Person Table.
but before every insertion,i want truncate the person Table.
I have try it out with linking Execute Sql task to Data flow task.But it is showing error that a Primary Foreign key relation exists there.
If I understand correctly, SSIS has nothing to do with your real problem, which is that you want to truncate a table that is referenced by a foreign key constraint. That question has already been answered: Cannot truncate table because it is being referenced by a FOREIGN KEY constraint?
If a table in sql server has foreign key references then you can't truncate. instead in your execute sql task use delete without a where clause.
delete from person_table
If you are really adamant about truncating the table, you could drop the foreign key constraints, then truncate the table then recreate the foreign key constraints. Providing of course, that the user you are running the package as has the privileges to do so.
Create an "Execute SQl" task and run DELETE FROM person
after this task, run your import.
DELETE FROM will give the same result as TRUNCATE TABLE, but if the table has a foreign key pointing to it, it cant be truncated. You have to use the delete command
You won't be able to delete either unless cascading deletes is turned on (or you delete the child records first). Why is this a problem you ask, why can't I do what I want to do? Because if you do then you may lose the integrity of the data. Suppose I have records in table2 which relate to records in table 1. Suppose further that table1 has an autogenerated id. If I could truncate that table, then I leave those records i ntable 2 hanging out without any record to reference them, they have become orphaned. Well but I'm putting the data back in you say. But then they will have new id numbers and you will still lose the relatinoship tothe related data.
Can you drop the FK and truncate and insert and recreate the FK. Yes you can but it is a poor practice and you should not unless you are also recreating those related records.
The best practice is to use a MERGE statement to update or insert depending on what you need.
In SSIS Transfer SQL Server Objects Task Set Property DeleteFirst to TRUE

How to ALTER a table on iSeries that has constraints? Getting "*FILE in use." error

I have a table on a iSeries(IBM-i/AS400) which has some constraints. The table is created with SQL like so, with a handful of foreign keys linking from other tables to this table (actual SQL has been a bit obfuscated here):
CREATE TABLE ABCLIB.ABCDE (
DEIDN INTEGER NOT NULL WITH DEFAULT,
DETTL VARGRAPHIC (50) ALLOCATE(25),
DETYP CHAR (1) NOT NULL WITH DEFAULT);
ALTER TABLE ABCLIB.ABCDE ADD PRIMARY KEY (DEIDN);
ALTER TABLE ABCLIB.ABCFG ADD FOREIGN KEY (FGDEK)
REFERENCES ABCLIB.ABCDE (DEIDN)
ON DELETE RESTRICT ON UPDATE RESTRICT;
ALTER TABLE ABCLIB.ABCHI ADD FOREIGN KEY (HIDEK)
REFERENCES ABCLIB.ABCDE (DEIDN)
ON DELETE RESTRICT ON UPDATE RESTRICT;
Now, much later, I will need to alter that table to add a field:
ALTER TABLE ABCLIB.ABCDE ADD COLUMN DEICN VARGRAPHIC (100) ALLOCATE(50)
Which results in this message:
Row or object ABCDE in ABCLIB type *FILE in use.
I have checked and there are definitely no object locks on this table at this time. When I check the joblog, I see this:
Constraint cannot be removed from file Q_AT000000.
Constraint(s) not removed from file Q_AT000000.
File ABCDE in ABCLIB not changed.
Row or object ABCDE in ABCLIB type *FILE in use.
Now, I could of course remove and re-add the constraints in question, but I feel like this should not be necessary. The column I am adding has nothing to do with the constraints. I believe this probably is a result of the fact that in fact OS400 (i5/OS) is not really altering the existing table but instead is creating a new table and copying data in, and that is probably where the pain comes in.
But is there a way to possibly suspend the keys and then resume them after the alter?
(Answers that do not involve doing this with SQL or suggest creating the table differently in the first place are not helpful as they are not applicable here...)
The answer is: I missed the fact that there was a lock on one of the tables that had a foreign key pointing to that table. Or, put more bluntly: I am an idiot!
Does Enabling or disabling referential constraints help?

What is the equivalent effect to Truncating a table, when the table is referenced by a foreign-key

Straight out of the MSDN docs for Sql Server 2005:
You cannot use TRUNCATE TABLE on tables that:
Are referenced by a FOREIGN KEY constraint.
Participate in an indexed view.
Are published by using transactional replication or merge replication.
I want the effect of a TRUNCATE (specifically the fact that it resets IDENTITY type columns), but I can't use one in my case because my table is referenced by a foreign-key elsewhere in the database.
Update: This is for a testing configuration where I am clearing out the referencing table as well, so foreign-key integrity is a non-issue.
What other ways are there to get around this?
You can delete all the rows and then do a DBCC CHECKIDENT (Tablename, RESEED, 0) to reset the identity seed
But again DELETE is fully logged while TRUNCATE is minimally logged and will be many times faster
Another option is to drop the foreign key constrains then do a truncate and then recreating the foreign key constraints
The fact that it is refernced by a foreign key is the clue you need to not truncate a table or you would be creating orphaned records. This is why truncate table is not allowed if a foreign key exists.
The correct process is to first delete the refernced records, if any, then drop the FK constraint, then truncate the table then reinstate the fk constraint. If you skip step one, you will create a data integrity nightmare where the record pointing to oldid 100 is not pointing to the new record that happens to get assigned to 100 and it isn;t the record it should match to.
You can drop the foreign key, truncate the table, and then recreate the foreign key.
You will need to drop the constraint, trunc the table, and then add the constraint back. However, you should be very careful with this. If there are rows in the table that you are dropping the FK reference to you will not be able to add it until those rows are deleted or the FK column in the other table is clear.