There is my table :
ID code(varchar)
1 006
2 008
3 005
4 010
5 002
I have created a stored procedure:
CREATE PROC pp
@code VARCHAR(10),
@new_code VARCHAR(10) OUTPUT
AS
BEGIN
SELECT TOP 1 @new_code = RIGHT(1000+code+1,3)
FROM tb AS a
WHERE [Code] >= @code
AND NOT EXISTS (SELECT 1 FROM tb WHERE [Code]=RIGHT(1000+a.[Code]+1,3))
ORDER BY RIGHT(1000+code+1,3)
END
When I call this stored procedure below the result is 011, it is correct:
DECLARE @code VARCHAR(3)
EXEC pp '009', @code OUTPUT
SELECT @code
When I call the stored procedure below, the result is 011 remain, so the result is wrong. It should be ‘004’.
DECLARE @code VARCHAR(3)
EXEC pp '003', @code OUTPUT
SELECT @code
How to correct this? TKS!
It probably has something to do with the fact that you are selecting top 1, and ordering by a field that is not a number, but is a varchar, when you are expecting the order by to behave like a number. Have you tried casting/converting the [Code] field to an int, and then ordering by that value?