asmgx
asmgx

Reputation: 7984

Compare string between 2 string values?

This is my script in SQL Server:

declare @From varchar='280'
declare @To varchar='289'
declare @Cnt int = 0

if LEFT('2810',3) BETWEEN @From AND @To
begin
    print('Hi')
end
else
begin
    print('Bye')
end

I know that '281' is between '280' and '289'

But this script always returns 'Bye' when it should return 'Hi'.

This script is a sample of bigger script which can have values such as 'T39', 'K92'

So I cannot use it as numeric 280 and 289.

How to compare string between 2 string values?

Upvotes: 1

Views: 74

Answers (1)

John Cappelletti
John Cappelletti

Reputation: 81930

Always define the length of a (n)varchar:

declare @From varchar(10)='280'
declare @To varchar(10)='289'
declare @Cnt int = 0

if LEFT('2810',3) BETWEEN @From AND @To
begin
    print('Hi')
end
else
begin
    print('Bye')
end

Returns

Hi

Without the length

declare @From varchar='280'
Select @From

Returns

2

Upvotes: 5

Related Questions