While the below code works I cannot help but think there is a cleaner way of doing this. The below query would eventually result in @represented_org being set to 10800. As I said this code works for orgs 00001 through xxxxx, but I just feel like it could be tightened up. Any help would be greatly appreciated.
Code:
declare @rowcount int,
@count int,
@assigned_org char(8),
@represented_org char(8)
set @assigned_org = '108271'
select @count = len(@assigned_org)
while 1=1
begin
select @rowcount = count(*)
from csr
where represented_org like substring(@assigned_org,1,@count)+'%'
if @rowcount > 0
break
if @count > 1
select @count = @count - 1
else
break
end
select @represented_org = a.represented_org
from csr a
where a.represented_org like substring(@assigned_org,1,@count)+'%'
select @represented_org