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?
Aaron’s post is not quite correct because it deletes everything in the table when there is no final agent. The question pretty clearly states that only things with the same account should be deleted. You can see this if you add the values “(5, ‘C’)” to the agent account records.
The following does the deletion only of accounts refered to by the final agent table:
I used the same naming convention as Aaron’s answer to clarify the difference. Check out what happens with: