you dont need a loop for this. see belowdeclare @test table(id int identity(1,1),val bigint)insert into @testvalues (270361),(2703612),(2703618)declare @inp bigintset @inp= 2703613020--2703612040select top 1 * from @test where CAST(@inp AS varchar(1000)) LIKE CAST(val as varchar(50)) + '%' ORDER BY LEN(CAST(val as varchar(50))) DESC
------------------------------------------------------------------------------------------------------SQL Server MVP