Search code examples
sql-serversql-delete

What is the error in DELETE query when using joins


Code is running fine when commenting DELETE statement and trying with SELECT statement. Please help

DELETE FROM 
--select * from 
Site as s
join 
(select SiteID,Code, Name, Dense_rank() over (partition by Code order by SiteID ) as Rank from Site
) as t 
on s.SiteID = t.SiteID
WHERE t.Rank != 1

Getting following error message

Msg 156, Level 15, State 1, Line 5
Incorrect syntax near the keyword 'as'.
Msg 156, Level 15, State 1, Line 8
Incorrect syntax near the keyword 'as'.

Solution

  • You can't alias a delete table, but delete can refer to an alias. Instead of this:

    delete from Site as s
    ...
    

    Try:

    delete from s
    from Site as s
    ...