Please start any new threads on our new site at https://forums.sqlteam.com. We've got lots of great SQL Server experts to answer whatever question you can come up with.

 All Forums
 General SQL Server Forums
 New to SQL Server Programming
 '10' < '2'

Author  Topic 

waterduck
Aged Yak Warrior

982 Posts

Posted - 2012-11-01 : 21:53:48
why below is valid?

if '10' < '2'
select 'valid'

answer not accepted. because they are not integer.

khtan
In (Som, Ni, Yak)

17689 Posts

Posted - 2012-11-01 : 22:00:30
Because you are doing a string comparison. '1' is less than '2'

To confuse you further, what is the result of the following ?
if '10' < 2 select 'valid' else select 'not valid'




KH
[spoiler]Time is always against us[/spoiler]

Go to Top of Page

khtan
In (Som, Ni, Yak)

17689 Posts

Posted - 2012-11-01 : 22:19:38
but a bit nasty here


KH
[spoiler]Time is always against us[/spoiler]

Go to Top of Page

waterduck
Aged Yak Warrior

982 Posts

Posted - 2012-11-01 : 22:44:55
so u mean string comparison is taking the first character to compare?
as if
'abc' vs 'b', 'a' as first character and 'b' as first character
'10' vs '2', '1' as first character and '2' as first character
'10' vs 2, '10' as string and is string is over numeric(1-0), therefore is after numeric(1-0) and 2 is is before string, therefore is under numeric(1-0).

i assume that numeric 1-0 is before any string.
Go to Top of Page

khtan
In (Som, Ni, Yak)

17689 Posts

Posted - 2012-11-01 : 23:39:58
when comes to sorting or comparison on string, it is based on the ascii code. So ascii code for '1' will comes before 'a'

select ascii('1'), ascii('a')


for '10' < 2 , it is comparing a string and integer. the string will be converted to integer before comparison as integer has a higher precedence [http://msdn.microsoft.com/en-us/library/ms190309.aspx]

You will get conversion error if you do this '10a' < 2


KH
[spoiler]Time is always against us[/spoiler]

Go to Top of Page

waterduck
Aged Yak Warrior

982 Posts

Posted - 2012-11-02 : 00:09:49
understood!
Go to Top of Page

madhivanan
Premature Yak Congratulator

22864 Posts

Posted - 2012-11-02 : 04:16:43
quote:
Originally posted by waterduck

why below is valid?

if '10' < '2'
select 'valid'

answer not accepted. because they are not integer.


Do not compare when data are actually not in original data type

Madhivanan

Failing to plan is Planning to fail
Go to Top of Page
   

- Advertisement -