简体   繁体   中英

Override SQL Server Default Sort Order

In order to correctly 'match' data to another data source, I'm looking to add something (perhaps a collation?) to this query in order to return results AZ 0-9 instead of 0-9 AZ as they are now.

SELECT TOP 1 order_id
FROM orders
WHERE order_id IS NOT NULL
ORDER BY order_id

Note that order_id is a nvarchar field.

For this example, I'm getting order 04394 instead of order ASK284 as I'm looking for.

This will force Alpha over Digits

SELECT TOP 1 order_id
FROM orders
WHERE order_id IS NOT NULL
ORDER BY case when order_id like '[0-9]%' then 1 else 0 end
        ,order_id

You can do this by ordering on a CASE expression with each condition:

Select      Top 1
            order_id
From        orders
Where       order_id Is Not Null
Order By    Case When Order_Id Like '[A-Z]%' Then 0 Else 1 End,
            Case When Order_Id Like '[0-9]%' Then 0 Else 1 End,
            Order_Id Asc;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM