0

In a SQL Server 2008 R2 database, given this schema:

AgentsAccounts
_______________
AgentID int UNIQUE
AccountID


FinalAgents
___________
AgentID

I need to create a query that does this: For each AgentID 'final' in FinalAgents remove all of the OTHER AgentID's from AgentsAccounts that have the same AccountID as 'final'. So if the tables have these rows before the query:

AgentsAccounts
AgentID    AccountID
1          A
2          A
3          B
4          B

FinalAgents
1
3

then after the query the AgentsAccounts table will look like this:

AgentsAccounts
AgentID    AccountID
1          A
3          B

What T-SQL query will delete the correct rows without using a curosr?

4

1 回答 1

2

Aaron 的帖子不太正确,因为当没有最终代理时,它会删除表中的所有内容。这个问题很清楚地表明,只有具有相同帐户的东西才应该被删除。如果将值“(5, 'C')”添加到代理帐户记录,您可以看到这一点。

以下仅删除最终代理表引用的帐户:

delete aa
from @AgentsAccounts aa join
     (select fa.AgentID, aa.AccountID
      from @FinalAgents fa join
           @AgentsAccounts aa 
           on fa.agentId = aa.agentId
     ) fa
     on fa.AccountID = aa.AccountID and
        fa.AgentID <> aa.agentID;

我使用与 Aaron 的答案相同的命名约定来澄清差异。看看会发生什么:

INSERT @AgentsAccounts VALUES (1,'A'), (2,'A'), (3,'B'), (4,'B'), (5, 'C');
于 2012-06-20T18:38:01.863 回答