The other day I was formulating a DELETE based on a sample I have in my notebook:
DELETE FROM Orders
FROM Customers c INNER JOIN Orders o ON c.CustomerID = o.CustomerID
WHERE Country = 'USA'
I mistyped it - and thereby deleted the whole table. I typed something like this:
DELETE FROM Orders
select c.* FROM Customers c INNER JOIN Orders o ON c.CustomerID = o.CustomerID
WHERE Country = 'USA'
SSMS regarded this as two separate queries - a delete query that deletes the whole table and then a subsequent SELECT. Was supposed to be one query.
Such a typo is a little less likely to occur if I could write the test version as a CTE using syntax something like this:
WITH JustDups AS
(
SELECT CustID FROM Customers WHERE CustID NOT IN
(
SELECT MIN(CustID) FROM Customers GROUP BY CustID HAVING Count(*) > 1
)
)
Select * from Just Dups
Then after testing it as a SELECT I'd just have to change the last SELECT to a DELETE. This is pretty safe as far as typos are concerned, but I gather that a CTE won't delete from a multi-table query?
So at this point I don't know a very safe way to write and test DELETE queries. If anyone has any suggestions, I'm all ears. Thanks in advance.