Remove content from SQL Server tables - sql-server

I have several tables with content. Is there a way how I can remove all the content without removing the keys (primary key, foreign key etc.) ?
When I say truncate or delete it obviously returns an error.
Cannot truncate table 'login' because it is being referenced by a FOREIGN KEY constraint.

You're right, you cannot run truncate table on an table which uses an foreign key. But you can run a normal delete on the table itself.
The only thing you should take care of is the order.
For example:
You have a table users and a table users_log where you store all users logins.
You cannot run the delete on the users table if still rows from users_log referencing them.
If you delete all rows from users_log and afterwards deleting the rows from users everything should be fine.
In this particular example, this code will work:
DELETE FROM users_log
DELETE FROM users
While this won work:
DELETE FROM users
DELETE FROM users_log -- which has a foreign key constraint on users

Related

Foreign Key with wordpress

I have a table (multisite network) where I use blog_id as one of the columns which is also needed on some of my custom php functions. Until now, I haven't used FK which should be appropriate for my tables.
So, can I FK to wordpress wp_blogs table? if yes, if ever I delete that blog will it also delete the entries on my other tables that references wp_blogs?
CREATE TABLE wp_blogs (blog_id INT NOT NULL...)
FOREIGN KEY (blog_id)
REFERENCES wp_options(blog_id)
ON DELETE CASCADE;
If you created a table like above then every time when blog_id will remove from wp_options then all rows from wp_blogs will remove too.
When you remove rows from wp_blogs then no rows won't remove from wp_options
Read about ON DELETE CASCADE in MySQL documentation.

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)

foreign key data deletion should display error for primary key

i have two tables Table1 and Table2. Where table1 column primary key is referred to table2 column as foreign key.
Now i have to display a error message of constraint violation when ever i delete records from table2 which is having foreign key column of table1.
If I get it right your column A (say) in table 1 references column B (say) in table 2.
What you can do is set the ON DELETE to NO ACTION which will prevent deletion of records from table 2 if any children of it still exists in table 1.
You can can do this by:
ALTER TABLE TABLE1 ADD FOREIGN KEY (A) REFERENCES TABLE2 (B) ON DELETE NO ACTION;
You don't have a constraint violation if you delete records from the child table and not the parent. It is normal to delete child records. For instance if I have a user table and a photos tables that contains the userid from the users table, why would I want to stop that action and throw an error if I want to delete a photo? Deleting a child record doesn't also delete the parent.
If you really want to do that, then you must do it through a trigger (make sure to handle multiple record deletes) or if the FK is a required field, then simply don't grant permissions to delete to the table. Be aware that this may mean you can never delete any records even when you try to delete. A simple method may be to not have a delete function available in the application.
I suspect what you really need to a to get a better definition of what is needed in the requirements document. In over 30 years of dealing with hundreds of databases, I have never seen anyone need this functionality.

Delete from multiple tables SQL

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?

SQL Server 2008 - Multiple Cascading FK's - Do i need a trigger?

I have a 1..* relationship between User and Post. (one user has many posts)
Post has a FK called "UserId", which maps to the "UserId" field on User table.
I tried to set this FK as Cascade UPDATE/DELETE, but i get this error:
'Users' table saved successfully
'Posts' table
- Unable to create relationship 'FK_Posts_Users'.
Introducing FOREIGN KEY constraint 'FK_Posts_Users' on table 'Posts' 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.
I have a table called PostHelpful. One Post has many Helpful's.
Helpful has a cascading FK to User (so when a User is deleted, their Helpful's are also deleted).
But i think this is the cause of complaint for "multiple cascade paths".
Because if i delete a User (currently), it will delete their helpfuls. But im trying to add a cacade to Post also, do it would delete the Post, then try and delete the Helpful's for that Post (as Helpful also has a cascading FK to Post). In that scenario, which cascading FK would SQL choose?
Here is the database diagram of the three tables in question:
As you can see, "PostHelpful" is a child to both "Post" and "User" (has FK's to both).
So i can't make both keys cascading? Do i need a trigger on "Users" (AFTER DELETE) to manually delete the helpfuls (and other tables referencing User).
It's not a matter of which path will SQL Server choose, it does not allow it so that it won't wind up in a compromising position. When we ran into this situation, we had to resort to a trigger.
1) As the error message stated, change the Users_PostHelpfuls FK to ON DELETE NO ACTION.
2) Add an INSTEAD OF DELETE trigger to Users:
CREATE TRIGGER dbo.Users_IO_Delete
ON dbo.Users
INSTEAD OF DELETE
AS
BEGIN;
DELETE FROM dbo.PostHelpfuls WHERE UserId IN (SELECT UserId FROM deleted);
DELETE FROM dbo.Users WHERE UserId IN (SELECT UserId FROM deleted);
END;
Now, the FK will still enforce DRI, but the trigger is cascading the delete rather than the FK constraint.
You could replace PostHelpfuls with Posts in the above steps. But when doing this it's best to use the trigger to remove the less independent entity's records. In other words, it's more likely that Posts are related to tables beside Users and PostHelpfuls than PostHelpfuls is related to tables beside Users and Posts.

Resources