How can a SQL query have two from clauses?

前端 未结 3 1073
刺人心
刺人心 2021-01-17 16:24

This just looks so odd to me:

delete from GearsDev.dbo.Products 
from GearsDev.dbo.Products as C
inner join #Common as M
    on M.item = C.ItemNumber
         


        
相关标签:
3条回答
  • 2021-01-17 16:57

    You can constrain the set of records you want to delete by more than one table. The second from just generates the alias C for the table you delete from, joins it with the table #common and deletes only records which have a record in talbe #common.

    0 讨论(0)
  • 2021-01-17 16:59

    As can be seen from the documentation of DELETE, it can take two FROM clauses.

    The first FROM:

    FROM: Is an optional keyword that can be used between the DELETE keyword and the target table_or_view_name, or rowset_function_limited.

    The second FROM:

    FROM <table_source>: Specifies an additional FROM clause. This Transact-SQL extension to DELETE allows specifying data from and deleting the corresponding rows from the table in the first FROM clause.

    This extension, specifying a join, can be used instead of a subquery in the WHERE clause to identify rows to be removed.

    So, the SQL will delete records from the Products table that have a matching item when it is joined with #common.

    This is equivalent (in meaning) to the following query:

    delete from [GearsDev].[dbo].[Products]
    where ItemNumber in
    (
      select item from #common
    )
    
    0 讨论(0)
  • 2021-01-17 17:00

    From MSDN The second from allows you create a filter that corresponding rows in the first from are deleted where they match.

    In this case Delete all [GearsDev].[dbo].[Products] where ItemNumber has a corresponding row in #Common with the item of the same value

    0 讨论(0)
提交回复
热议问题