How to use DELETE with EXCEPT clause?

荒凉一梦 提交于 2019-12-13 18:59:17

问题


I'm trying to do some ETL from some single tenant DBs (per client) to a multi-tenant DB (all clients, or "global"). In the global DB, I'm trying to maintain a lookup table that identifies users that are associated with a client. So I have this:

Database: Global
Tables: Users and ClientUsers

Database: Client
Tables: Users

After some other ETL operations, I want to clean up the ClientUsers table by deleting any Users that no longer exist in the Client.Users table. I thought this would work:

DECLARE @ClientID varchar = 'ClientA'

DELETE FROM Global.dto.ClientUsers
SELECT ClientID, UserID FROM Global.dto.ClientUsers WHERE ClientID=@ClientID
EXCEPT
SELECT ClientID=@ClientID, UserID FROM ClientA_DB.dbo.Users

But this deletes ALL records. I tested the individual select statements, and they return what I expect for my first test, where there are none to delete. Both select statements return the exact same dataset. Which to me means that no records should be deleted. Right? Apparently, I'm missing some basic understanding or a nuance as to how EXISTS works, because this seems like it should be straightforward!

I realize its possible to do this using other methods, but I'm stumped why EXCEPT doesn't work like I think it should.


回答1:


The reason it isn't working is that you're actually running two statements sequentially. Think of your code more like:

DECLARE @ClientID varchar = 'ClientA'

DELETE FROM Global.dto.ClientUsers;

SELECT ClientID, UserID FROM Global.dto.ClientUsers WHERE ClientID=@ClientID
EXCEPT
SELECT ClientID=@ClientID, UserID FROM ClientA_DB.dbo.Users;

If you want to modify the Delete statement, you need to follow it with a Where, Join, etc.

For some alternative methods to get the result you want, see the excellent answers at: Using T-SQL EXCEPT with DELETE / Optimizing a query



来源:https://stackoverflow.com/questions/55423803/how-to-use-delete-with-except-clause

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!