Sort varchar as number when it can also be a mix of numbers and letters

StackOverflow https://stackoverflow.com/questions/18822239

  •  28-06-2022
  •  | 
  •  

سؤال

The following sorts CustomerNo in the following order: (1,2,3,10,20,400), which is what is intended. But I get an error when inserting a non-numerical CustomerNo, such as 1a. the problem is the WHERE clause, where CustomerNo > 1.

Conversion failed when converting the varchar value '1a' to data type int.

I don't particulary care where non-numerical CustomerNo's are placed in the order. I just don't want it to fail. If I remove the WHERE clause, I always get the order (1,2,3,10,20,400, 1a), but then with the SELECT TOP 1 *, I always get the row where CustomerNo=1. I would like to get the next one.

SELECT TOP 1 *
FROM [Database].[Company].[Table]
WHERE CompanyNo = 804
  AND CustomerNo > 1
ORDER BY 
  CASE IsNumeric(CustomerNo) 
    WHEN 1 THEN Replicate('0', 100 - Len(CustomerNo)) + CustomerNo 
    ELSE CustomerNo
  END
هل كانت مفيدة؟

المحلول

This is how I did it (adjust it to your column length):

CASE IsNumeric(site_id) WHEN 1 THEN REPLACE(STR(site_id, 8, 0), ' ', '0') ELSE site_id END
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top