conflict occurred when delete one rows in my database - sql

I have two table.
tbl_User and tbl_Follow for create relationship many to many
Like a picture
http://i.imgur.com/5JGsfSU.jpg
I don't set Action Delete or change Roles
When i delete one row in table user sql alert error conflict.

As per the attached image there is a foreignkey realtionship between the tables tbl_User and tbl_Follow through the column id (tbl_User) and userid (tbl_Follow). For every row in tbl_Follow there is will be an entry in tbl_User with same value in columns id and userid. But it is not necessary in vice versa.
I think you are deleting a row in tbl_Users which has an entry in tbl_Follow. First delete the row in tbl_Follow then proceed to tbl_Users.
Also you can confirm the foreignkey relationship through:
Type "tbl_Follow", select the table name and press "ALT+F1" you can view a set of results where refer the resultset with columns constraint_type,name etc. There shows the foreignkey defined for the table.

Related

Delete rows from multiple tables due to data from one table

I have multiple tables that I need to delete rows from and they are all contingent on data from one table. For instance, I have a Users Table and in the Users Table the Users have a UserId. I am trying to get rid of all the data that is in relation to that one user in all the other tables.
For instance, there is a Members Table and in the Members table, there is a Foreign Key relationship to the Users table so it's tied by the UserId. The Members table can have multiple members associated with the UserId (A User can be members to more than one thing so it's a one to many relationship). Then there is also a Permissions table and in the Permissions table it has a foreign key relationship to the Members table. And in that table the Members can have multiple permissions (A Member can have permissions to more than one thing is that's a one to many relationship).
What I am needing to do is delete all the rows in the Permissions table that are in relation to the all the MemberId's that are in relation to the UserId from the User's Table (i.e. - Bob has a UserId of 7 and in the Members Table he is a Member of 3 things so he has 3 MemberId's associated to his name and in the Permissions Table those 3 MemberIds also have 3 Permissions associated to those 3 MemberIds. I am needing to delete all 9 Permission rows according to those 3 MemberIds, then delete all the 3 Member rows according to the 1 UserId, and then delete the one UserId according to a UserName).
I've tried to Inner Join multiple tables and also connect them with Unions but I am having difficulty of tying all those tables down to that one UserId and carrying that data through the flow of logic.
User has a UserId of 7
User is is associated with 3 MemberId's
The MemberId is associated with multiple PermissionId's
So I need to delete all those PermissionId's (I did a WHERE statement just on the User's MemberId's), all 3 instances of the MemberId's, and the User.
If you are aware of UserID that you want to delete from different table, then this is easy to handle from table Users and Members. You need to use a Sub Query when you will delete records from Permissions table. But if there are relation (PK/FK) established between tables, you need to maintain some sequence as below-
Important Note: Delete is a risky operation unless you have proper Backup. So please try to execute scripts on test data first.
At first you have to delete records from Permission table with following script-
DELETE FROM Permissions
WHERE MemberID IN
(
SELECT MemberID FROM Members
WHERE UserID = 7
)
In second step, you have to delete records from Members table as below-
DELEET FROM Member WHERE UserID = 7
In third step, you have to delete users from Users table as below-
DELETE from Users WHERE UserID = 7

Inserting data into two different tables with SQL Server 2008?

I have three tables in my database: Contacts (master table), Users and Staff. The Contacts table has a primary key that is referenced as a foreign key from the Users and Staff tables.
Contacts
ContactID (Primary Key)
First Name
Last Name
Email
Users:
ContactID (Foreign Key)
Username
Password
Staff:
ContactID (Foreign Key)
Position
Comments
Pulling data from these tables is fairly simple with INNER JOIN and depends what data you need from the Users or Staff table. Updating and inserting new records is something that I'm not sure which way to approach.
Since the Contacts table is my master table and holds unique ID's but at the same time is shared between Users and Staff, I'm not sure about this situation.
Let's say I want to enter new user record. I need to enter First, Last name and email into the Contacts table, and User Name and Password into the Users table. At the same time I have to check if First, Last name and email already exist in the Contacts table, since maybe this Contact record has been previously entered for a Staff record.
I'm not sure how to prevent duplicates but at the same time there might be user or staff with the same name. Should I limit/filter by email and not let them enter the records if the email already exist in contacts table? Or is there a better way to handle this?
The whole point of having three tables is to prevent redundant data since User might be a Staff, but Staff might not be a User if that make sense. If anyone can help me pick the best approach please let me know. Thanks
You have to start by using a SELECT query and whatever business rules you want to test to decide if you will perform the INSERT at all, or UPDATE an existing record instead.
Then if you are going to INSERT, you have to INSERT into Contacts first, get the newly inserted ID, and then INSERT into the other two tables.

SQL Server Trigger on Deleted - Which records are in deleted table?

I'm new to triggers, but I'm having a hard time understanding if I'm taking the right approach here.
I'm using SQL Server 2016. I have 2 tables, Teams and TeamMembers. Teams is the parent table and TeamMembers is the child, using Teams.TeamID as a foreign key.
I also have an Activities table that logs any creates or updates to any of my tables. This table has a TableName text column as well as an IdRow column that references the ID of the row that gets created or updated. I've also got a JSONChanges column which contains a JSON string of what was changed in that activity log item.
So there's only 1 record for each Activity on a table. But potentially many activities performed per record.
So, when a user deletes a team, I need to not only delete all of the Activities logged for that team and the Team Members for that team (which is easy to do within my Team_Delete stored procedure), but I also want to delete any records in my Activities table for the activities on the TeamMembers. Since the Activities table's IdRow column points at the TeamMemberID column in the TeamMembers table, I can't use the TeamID from the delete stored procedure.
My thought was to just create a delete trigger on the TeamMembers table.
Whenever a TeamMember was deleted, I could just delete all of the records in the Activities log that point to the record that was deleted. That would simplify my Team_DELETE stored procedure. I think.
The confusion I have has to do with the records that will be in the deleted table at any given time. If User A deletes a TeamMember, and at the same time, User B runs an Update on another Team Member, won't the deleted table have 2 records in it? If I delete all records in my Activities Table based on what's in the deleted table, then I'm deleting records I shouldn't be deleting. Right?
The other issue is how do I pick just one record to delete? How do I know which record in the deleted table is the one I want from the trigger?
If I had to use a trigger on TeamMembers , I would try:
CREATE TRIGGER [ schema_name .]DeleteTeamMemberActivities ON [ schema_name .]TeamMembers
AFTER DELETE
AS
DELETE
FROM
Activities a
INNER JOIN DELETED d ON d.TeamMemberID = a.IdRow AND a.TableName ='TeamMembers';
I would also use the cascading delete on the foreign key relation between Team and TeamMembers.
[edited 08/09/2017 12:45 correcting the a.TableName join]
FYI, I edited cclarke's code a little bit - here's what I ended up with:
CREATE TRIGGER TRIGGER_DeleteTeamMemberActivities ON TeamMembers
AFTER DELETE
AS
DELETE a
FROM
Activities a
INNER JOIN deleted d ON d.TeamMemberID = a.IDRow AND a.TableName
='TeamMembers';

Why I can't delete the records from this table?

I am pretty new in Microsoft SQL Server and I am not so into DB and I have the following problem.
I have to delete all the records that are inside a table named VulnerabilityReference
So I executed this statment:
delete from VulnerabilityReference;
But I obtain this error message and no rows are deleted form my table:
Msg 547, Level 16, State 0, Line 1
The DELETE statement conflicted with the REFERENCE constraint "FK_AlertDocument_Reference_Reference". The conflict occurred in database "DB NAME", table "dbo.VulnerabilityAlertDocument_VulnerabilityReference", column 'VulnerabilityReferenceId'.
The statement has been terminated.
What it exactly means? Have I to delete all the records from the VulnerabilityAlertDocument_VulnerabilityReference table before delete the records into my VulnerabilityReference?
Tnx
Andrea
The table you are attempting to delete has it's primary key in another table. You must first remove (or set to null) the column in the other table BEFORE you can delete. This is called DB Referential integrity.
You can disable constraints (if you have adequate permissions) but I would suggest you not do that.
To remove the link for all records in that other table, you could do this:
UPDATE VulnerabilityAlertDocument_VulnerabilityReference
SET VulnerabilityReferenceId = NULL
If the AlertDocument table does NOT ALLOW nulls for that column then you'll need to DELETE all the VulnerabilityAlertDocument_VulnerabilityReference records etc... OR ALTER the table to ALLOW NULL. Make sure you know what you are about to do...
I am assuming the name of the column in the VulnerabilityAlertDocument_VulnerabilityReference table, you obviously need to use the correct table and column names.
This error is because you have an id of a record in VulnerabilityReference related to a AlerDocument table. The error is warning you of this problem and that you can't delete this record if you don't delete first the related records.
I mean the tables in the relation named as FK_AlertDocument_Reference_Reference
You have a relationship between VulnerabilityAlertDocument_VulnerabilityReference and other table. You can go to this table and find the relationships, find the name beginning with FK. In the properties of this relationship you will see the name of the other table and columns used in this relationship. If you want you can create a diagram, then drop this two tables and you will see in a visual way how the relationship is built

Moving and Deleting rows in MySQL

I have created two tables in MySQL which are called "birthTable" and "deathTable". When I add a person in deathTable which she/he was in birthTable, I want to delete his/her name and family from birthtable because I add him/her in deathTable. But I don't know how I can do that?
What you describe can be done manually or with triggers, but generally you should not do it.
You should have a table called people, and then simply mark them as dead or alive. Instead, you may also create two columns for their birthday and deathday, if you intend to store this information.
In general, you shouldn't be moving records simply because some attribute about them has changed.
This is the SQL:
DELETE FROM birthTable WHERE id = ...
where id is the name of some identifying field.
Here is the documentation for DELETE.
What you have to do is construct a DELETE FROM-query. If you only want to delete one row from a table, you need to be certain that the parameters you give it are unique for that row. Usually this is done by having a column called id. Then, knowing the id, all you have to do is this:
DELETE FROM table WHERE id=<your id>;
I think that in your case you could just have a table called "people", and a boolean column "alive" which is 1 if the person is alive and 0 if the person is dead.
If you still want to delete one row from your birthTable, assuming you know the name of this person, you do it like this:
DELETE FROM birthTable WHERE firstName=<first name> AND lastName<last name>;
I've assumed that the column names for first and last names are firstName and lastName, you'll have to modify this to match your column names. This will delete any entry in the birthTable which matches the critera (could be more than one, if you have for example 2 people called Alan Johnson).
Hope that helps. :)
You can write trigger on insert on table deathTable which deletes corresponding row from birthTable.
CREATE TRIGGER trg_deathTable_insert
BEFORE INSERT ON deathTable
FOR EACH ROWS
BEGIN
DELETE FROM birthTable WHERE person_id = NEW.person_id;
END;
DELETE FROM birthTable WHERE id = xxx