I want to delete rows based on the combination of two columns. My table looks like this (simplified):
[ID], [Sub_ID], [Value]
Values could for example be:
1234 - 1 - 100
1234 - 2 - 50
5678 - 1 - 90
4321 - 1 - 75
4321 - 2 - 75
I want to delete all records except for some specific combinations of [ID] and [Sub_ID]. Example: delete all combinations except for combination 1234-2 and 4321-2.
*EDIT: The 2 values are an example, in reality I need to maintain well over 10,000 combinations of ID-Sub_ID.
To do this I combine the two ID columns with a cast and delete everything that does not match this combination.
Delete
from table
where
CAST(ID as varchar(4))+'-'+Cast(Sub_ID as varchar(1)) not in
('1234-2', '4321-2')
This works, but it is slow and probably very inefficient. It already takes several minutes to execute this query and I will expand the selection each month, probably making it even worse each time, Does anyone know how I can make this more efficient?
Many thanks, Steven