Click here to Skip to main content
15,898,134 members
Please Sign up or sign in to vote.
4.00/5 (1 vote)
See more:
Hello all,
Thanks for reading my thread,

let me brief you first. I have a table "Activity_id"
and in the table i have a column name "activity_id" nvarchar(6)
it just contains Serial No.s from 1 to 201.

Now the issue.
select max(activity_id) from activity_id
This query returns value "99" which is incorrect.
select max(cast(activity_id as int)) from activity_id
This query returns the value "201". which is correct.

I can reckon that its because of nvarchar and casting to int. but will u plz elaborate how nvarchar values are compared so that 99 is greater than 201.

Thanks,
Ahsan Ashfaq
Posted

1 solution

Firstly,
If "activity_id" contains serial nos from 1 to 201 then why is it a 'nvarchar(6)' type of column? Bad DB design!

Well the doubt you have regarding the query result must be something like:
first character of activity_id comparsion followed by 2nd, 3rd...
So, in 99 & 201:
99-> 1st = 9
201-> 1st = 2

9 > 2 => thus this results in 99 instead of 201.

Instead of casting in the query, best would be to change the column type to desired value types.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900