Jump to content

Recommended Posts

Hi aces,

I'm fairly new to SQL and I have the following question.  In one of my tables there is a colomn set as varchar.  Only it contains only numeric values (with one exeption).  When i'm trying to order by this colomn my result is like this: 1, 100, 1000, 2, 200 and not 1, 2, 100, 200, 1000.  This is logic because the values are char and not int.  So I've tried to convert them into an number like so:

 

SELECT T1.Person_ID, T1.Person_Name,
             T2.Organisation_ID
FROM tb_Persons AS T1
JOIN  tb_organisations AS T2
   ON   T1.Person_ID = T2.Organisation_ID
WHERE T2.Organisation_ID != 'MAIN'                    // avoid the only alfanumeric exception in the col.
ORDER BY CAST(T2.Organisation_ID AS INT);

This is the result:

You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'INT)' at line 7

 

In the same way I've tried "ORDER BY CONVERT(INT, T2.Organisation_ID)" with the same errormsg.

 

Is this due to the one real alfanumeric value in the table because imho the order is executed on de resultset (thus without the 'main')?

 

Help is greatly appreciated...

 

Link to comment
https://forums.phpfreaks.com/topic/212258-string-to-int-conversion-fails/
Share on other sites

Ok, I figured it out, don't ask me how or why but it works...

ORDER BY (CAST(T2.Organisation_ID AS unsigned Integer);

This does the job.  The "unsigned" makes everything work...

 

this is the reason why it works and your previous intent don't.... read the allowed "types" below CAST in the function CONVERT

http://dev.mysql.com/doc/refman/5.0/en/cast-functions.html#function_cast

 

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.