How do I sort a VARCHAR column in SQL server that contains words and numbers? -


I have a varchar (100) field that contains both letter and number values ​​usually car 1, car 10, car 100, car are in the form of 20. But values ​​can have a word before the number. Is there a way to sort these values ​​numerically so that the car 2 car comes before 10? Thank you.

You have to find out in your data and have to split the car 2 In a varchar car and int 2 .

The pattern can be as simple as Word SPACE NUMBER and you can set it to SPACE based on PATINDEX or Based on CHARINDEX , you can split with SUBSTRING .

You can then sort by two columns.

Here is an example

  Set Knitting @ Tail Tables (ID INT Identity (1, 1), String Value Worker (30)) @Table (StringValue) values INSERT @TableValue VALUES ('CAR 20') INSERT @Table (StringValue) VALUES ('CAR 2') INSERT INSERT @Table (StringValue) VALUES ('CAR 3') Enter in ('Car 10') (StringValue) Values ​​('Car 4') INSERT @Table (StringValue) VALUES ('SHIP 32') INSERT @Table (StringValue) 'Ship 310') INSERT @Table (StringValue) VALUES (' Ship 320 ') Enter @Table (StringValue) values ​​(' Ship 33 ') @Table (StringValue) values ​​(' Ship 34 ') SELECT Id, SubString (StringValue, 1, CharIndex ('', string value), object number, convert (INT, substring (string value, four indices ('', string value), LAN (string value)) Object ID @ 2 to 3 (String, value, '', string value), convert (INT, substring (string value, churnedx ('', string value), LN (str) by the object ID, string value @ string order @ string order Ingvalue)))  

Comments

Popular posts from this blog

MySql variables and php -

url rewriting - How to implement the returnurl like SO in PHP? -

kernel - How to create a "Block device" in Windows -