Difference between DELETE and DELETE FROM in SQL?

后端 未结 2 1283
梦如初夏
梦如初夏 2021-01-17 11:36

Is there one? I am researching some stored procedures, and in one place I found the following line:

DELETE BI_Appointments
WHERE VisitType != (
    SELECT T         


        
2条回答
  •  挽巷
    挽巷 (楼主)
    2021-01-17 12:00

    Assuming this is T-SQL or MS SQL Server, there is no difference and the statements are identical. The first FROM keyword is syntactically optional in a DELETE statement.

    http://technet.microsoft.com/en-us/library/ms189835.aspx

    The keyword is optional for two reasons.

    First, the standard requires the FROM keyword in the clause, so it would have to be there for standards compliance.

    Second, although the keyword is redundant, that's probably not why it's optional. I believe that it's because SQL Server allows you to specify a JOIN in the DELETE statement, and making the first FROM mandatory makes it awkward.

    For example, here's a normal delete:

    DELETE FROM Employee WHERE ID = @value
    

    And that can be shortened to:

    DELETE Employee WHERE ID = @value
    

    And SQL Server allows you to delete based on another table with a JOIN:

    DELETE Employee
    FROM Employee
        JOIN Site
           ON Employee.SiteID = Site.ID
    WHERE Site.Status = 'Closed'
    

    If the first FROM keyword were not optional, the second query above would need to look like this:

    DELETE FROM Employee
    FROM Employee
        JOIN Site
           ON Employee.SiteID = Site.ID
    WHERE Site.Status = 'Closed'
    

    This above query is perfectly valid and does execute, but it's a very awkward query to read. It's hard to tell that it's a single query. It looks like two got mashed together because of the "duplicate" FROM clauses.

    Side note: Your example subqueries are potentially non-deterministic since there is no ORDER BY clause.

提交回复
热议问题