views:

1133

answers:

5

I have a column containing the strings 'Operator (1)' and so on until 'Operator (600)' so far.

I want to get them numerically ordered and I've come up with

select colname from table order by 
cast(replace(replace(colname,'Operator (',''),')','') as int)

which is very very ugly.

Better suggestions?

+2  A: 

It's that, InStr()/SubString(), changing Operator(1) to Operator(001), storing the n in Operator(n) separately, or creating a computed column that hides the ugly string manipulation. What you have seems fine.

Joel Coehoorn
A: 

My answer would be to change the problem. I would add an operatorNumber field to the table if that is possible. Change the update/insert routines to extract the number and store it. That way the string conversion hit is only once per record.

The ordering logic would require the string conversion every time the query is run.

A: 

Well, first define the meaning of that column. Is operator a name so you can justify using chars? Or is it a number?

If the field is a name then you will use chars, and then you would want to determine the fixed length. Pad all operator names with zeros on the left. Define naming rules for operators (I.E. No leters. Or the codes you would use in a series like "A001")

An index will sort the physical data in the server. And a properly define text naming will sort them on a query. You would want both.

If the operator is a number, then you got the data type for that column wrong and needs to be changed.

Ricardo C
+1  A: 

If you really have to leave the data in the format you have - and adding a numeric sort order column is the better solution - then consider wrapping the text manipulation up in a user defined function.

select colname from table order by dbo.udfSortOperator(colname)

It's less ugly and gives you some abstraction. There's an additional overhead of the function call but on a table containing low thousands of rows in a not-too-heavily hit database server it's not a major concern. Make notes in the function to optomise later as required.

Cruachan
A: 

Indexed computed column

If you find yourself ordering on or otherwise querying operator column often, consider creating a computed column for its numeric value and adding an index for it. This will give you a computed/persistent column (which sounds like oxymoron, but isn't).

Constantin