I have the following query to update a table record setting new foreignKey if that foreignKey and foreignKey2 did not already exist. This should work great, however, how can I modify to delete that particular pkID record if it DOES exist?
table structure:
+----------------+
| table |
+----------------+
| pkID |
| foreignKey |
| foreignKey2 |
+----------------+
query:
UPDATE table a
SET a.foreignKey = 2
WHERE a.pkID = 1234
AND NOT EXISTS (
SELECT 1
FROM table b
WHERE b.foreignKey = 2
AND b.foreignKey2 = a.foreignKey2
)
You can delete if it exists, and only insert (instead of update since the record doesn't exist to be deleted) otherwise. But it is not clear what the 3rd value should be.
DELETE tbl where pkID = 1234;
if @@ROWCOUNT = 0
INSERT tbl(foreignKey, pkID, foreignKey2)
VALUES (2, 1234, ??)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With