SQL Delete Query Foreign Key constraint - sql

I am trying to Delete record with primary key as foreign key in two tables. Everytime I try to run the query it gives me this error:
Query:
DELETE FROM BusinessPlus_Post
FROM BusinessPlus_Post
INNER JOIN BusinessPlus_PostImage ON BusinessPlus_Post.Post_ID = BusinessPlus_PostImage.BusinessPlusPost_ID
INNER JOIN BusinessPlus_PostTag ON BusinessPlus_Post.Post_ID = BusinessPlus_PostTag.BusinessPlusPost_ID
WHERE
(BusinessPlus_Post.Post_ID = 3)
AND (BusinessPlus_PostImage.BusinessPlusPost_ID = 3)
AND (BusinessPlus_PostTag.BusinessPlusPost_ID = 3)
Error:
The DELETE statement conflicted with the REFERENCE constraint
"FK_BusinessPlusPostImage". The conflict Occurred in database
"BusinessPlus_AdminPanel_Database", table
"dbo.BusinessPlus_PostImage", column 'BusinessPlusPost_ID'. The
statement was terminated.

Right now, you are only stating that you want to delete the BusinessPlus_Post record, but not the BusinessPlus_PostImage and BusinessPlus_PostTag records. This would lead to problems, as we then would have 'orphan' PostImage and PostTag records with no corresponding Post records.
Apparently, it is not possible to delete from multiple tables in SQL Server (it is supported in MySQL, for example).
You have to split your queries, and delete from the 'child' tables first:
DELETE FROM BusinessPlus_PostImage
WHERE BusinessPlusPost_ID = 3
DELETE FROM BusinessPlus_PostTag
WHERE BusinessPlusPost_ID = 3
DELETE FROM BusinessPlus_Post
WHERE Post_ID = 3

Error: The DELETE statement conflicted with the REFERENCE constraint
"FK_BusinessPlusPostImage". The conflict Occurred in database
"BusinessPlus_AdminPanel_Database", table
"dbo.BusinessPlus_PostImage", column 'BusinessPlusPost_ID'. The
statement was terminated.
Error denotes that you have data referencing the foreign ,hence you cannot delete.
Delete the datas in BusinessPlus_AdminPanel_Database table
dbo.BusinessPlus_PostImage, column BusinessPlusPost_ID ,and then try delete

Related

Having error while executing postgresqlquery

I am facing error in my query while deleting row from two table which have same primary and foreign key :
Query:
DELETE FROM TABLE1 INNER JOIN TABLE2 ON (TABLE1.id=TABLE2.id) WHERE TABLE1.id='21306';
ERROR: syntax error at or near "INNER"
Using rdbms POSTGRESQL
You can't have a join in the from clause of a delete in Postgresql (although this is supported in SQL Server). Any additional table that you want to participate in the delete must be added to the using clause. Try this instead:
DELETE FROM TABLE1
USING TABLE2
WHERE (TABLE1.id=TABLE2.id) AND TABLE1.id='21306';

Update query error

I am trying to update records in table tciSTran that are present in the table tarRecurInvcLineDS
Here is the query I wrote...
update [mas500_test_app].[dbo].[tciSTaxTran]
set STaxSchdKey = 310
where STaxTranKey in
(select STaxTranKey from [mas500_test_app].[dbo].[tarRecurInvcLineDs]
I'm getting this error
Unable to update the tciSTaxTran record because it is trying to reference a record in tciSTaxSchedule that does not exist.
Seems you have a foreign key between tciSTaxTran.STaxSchdKey and the tciSTaxSchedule table. Does the tciSTaxSchedule table have a row with a primary key of 310?

Converting Pseudocode to SQL Script

So I have two tables:
Bookmarks has a few columns [id, etc.]
Person_Bookmark has 2 columns [personId, bookmarkId]
Bookmarks represents links to other websites. All valid bookmarks have an id. The Person_Bookmark table has a bunch of personIds and their bookmarks, shown as bookmarkId.
Here's my pseudocode:
> let x = integer list of all bookmarkId's from Person_Bookmark
>
> for each x {
> if ('select * from 'Bookmarks' where 'id' = x returns 0 rows) {
> delete from 'person_bookmark' where 'bookmarkId' = x
> }
> }
Please advise me how to convert to a Postgres [edit] SQL script.
#Jan mentioned foreign keys already, but his advice is incomplete.
Seems like you want to delete all associations to a bookmark that does not exist (any more).
Define a foreign key constraint in the form of:
ALTER TABLE person_bookmarks
ADD CONSTRAINT pb_fk FOREIGN KEY (bookmarkid) REFERENCES bookmarks (id)
ON UPDATE CASCADE
ON DELETE CASCADE;
This only allows values in person_bookmarks.bookmarkid that exist in bookmarks.id.
ON UPDATE CASCADE changes corresponding values in person_bookmarks.bookmarkid when you change an entry in bookmarks.id
ON DELETE CASCADE deletes corresponding rows in person_bookmarks.bookmarkid when you change an entry in bookmarks.id.
Other options are available, read the manual.
The ON DELETE CASCADE clause does automatically, what you are trying to fix manually. Before you can add the fk constraint you'll have to fix it manually once:
DELETE FROM person_bookmarks pb
WHERE NOT EXISTS (SELECT 1 FROM bookmarks b WHERE b.id = pb.bookmarkid);
-- OR NOT EXISTS (SELECT 1 FROM persons p WHERE p.id = pb.personid);
Deletes all rows with non-existing bookmarkid. Uncomment the last line to get rid of dead persons, too.
This works in SQL Server - not sure about MySQL...
delete pb
from
person_bookmark pb
where not exists (select 1 from booksmarks b where b.id = pb.bookmarkid)
Another version of #Derek's reply:
DELETE FROM person_bookmark
WHERE bookmarkid NOT IN (SELECT id FROM bookmarks)
The need to do this implies that you have no foreign key indexes between your tables. I strongly advise you to do so. The drawback (or feature) lies in that when you for example delete a person (I'm guessing this table exists from your example), you have to delete all associated data first, otherwise the server will throw an error.
Something like this:
DELETE FROM person_Bookmark WHERE personid = #personid
DELETE FROM person_SomeOtherTable WHERE personid = #personid
DELETE FROM person WHERE id = #personid
The advantage though is that you'll have no orphan rows in your database, and you can't enter erroneous data by mistake (store a bookmark for a person that doesn't exist).

Delete trigger not being executed

I have a table Absence with an PK AbscenceId (yes spelling mistake). I have another table Note, with an FK into Absence called AbsenceId (spelled correct this time). The FK constraint is:
ALTER TABLE [dbo].[Note] WITH CHECK ADD CONSTRAINT [FK_Note_Absence] FOREIGN KEY([AbsenceId])
REFERENCES [dbo].[Absence] ([AbscenceId])
GO
When an Absence is deleted, I want all Notes to go with it. I couldn't do this with CASCADES, because a Note can belong to something else as well.
So I created a trigger to delete the notes when an Absence is deleted:
ALTER TRIGGER [dbo].[TR_OnAbsenceDelete] ON [dbo].[Absence]
FOR DELETE AS
DELETE FROM [Note]
WHERE AbsenceId IN ( SELECT AbscenceId FROM Deleted )
But when I delete an Absence that has a Note attached to it, I get:
Msg 547, Level 16, State 0, Line 1
The DELETE statement conflicted with the REFERENCE constraint "FK_Note_Absence". The conflict occurred in database "ReturnToWork", table "dbo.Note", column 'AbsenceId'.
The statement has been terminated.�
It is almost like the trigger is not getting executed?
Your trigger needs to be written as an INSTEAD OF trigger, deleting first from Note and then from Absence.
CREATE TRIGGER [dbo].[TR_OnAbsenceDelete] ON [dbo].[Absence]
INSTEAD OF DELETE AS
BEGIN
DELETE FROM n
FROM deleted d
INNER JOIN Note n
ON d.AbscenceId = n.AbsenceId
DELETE FROM a
FROM deleted d
INNER JOIN Absence a
ON d.AbscenceId = a.AbscenceId
END
The problem is when you try to delete record from absence it fails because of the reference constraint. If the delete is success then your delete trigger will be called.
Also as suggested in this link you can try the instead of How can I fire a trigger BEFORE a delete in T-SQL 2005?

SQL Server : Changing an ID to an already existing one (merge) HOW TO?

I have two records that are the same in a table (entered by mistake). Both IDs are used as foreign key in other tables. I want to update the foreign keys to one "orignal" element and delete the other one. The problem is that it's possible that the UPDATE of the foreign key will generate a constraint exception (if the foreign key with the original element already exists).
So I would do something like :
UPDATE foreignTable SET id=1 WHERE id=2
DELETE FROM firstTable WHERE id=2
The problem is with the UPDATE, I would like to do the UPDATE if the row doesn't already exists, if yes just DELETE the row. How do you do that?
UPDATE ft
SET id = 1
FROM foreignTable ft
LEFT JOIN foreignTable ft2
ON ft.PrimaryKey = ft2.PrimaryKey
AND ft2.id = 1
WHERE ft.id = 2
AND ft2.PrimaryKey IS NULL
DELETE FROM foreignTable
WHERE id = 2
If you are using SQL Server 2008, have a look at the MERGE statement.
It allows you to insert the missing rows, update the existing one and delete those who have to be deleted.
http://technet.microsoft.com/en-us/library/bb510625.aspx
If you use an older version, you will have to copy your data to a temporary table, delete the data from the existing one and reinsert from the temp table.
Be sure to use a transaction and make a backup of your table to avoid data loss.