I'm going to sort an SQL server table by a column having following data:
2.5.1 Sonstiges
1.1.1 Pflegstandards
5.1.7 Arbeitsgemeinschaften
1.2.1 Anforderungen
2.4.5 Betriebsarzt
B Kernprozesse
1.1.1.4 Umgang mit
2.3.3 Kardiologie
......
as you see most of records begin with a number, but there are some starting with string as well. I use following query to cover both cases:
SELECT * from DocumentCategories
order by
case IsNumeric(replace( LEFT(name, CHARINDEX(' ', name)),'.',''))
when 0 then name
when 1 then cast(replace( LEFT(name, CHARINDEX(' ', name)),'.','') as int)
end
But I get an error regarding varchar to int conversion (because of record containg "B Kernprozesse"). So what's the role of case/when here? Have I missed anything?
I want the output to look something like below:
B Kernprozesse
1.1.1 Pflegstandards
1.2.1 Anforderungen
2.3.3 Kardiologie
2.4.5 Betriebsarzt
2.5.1 Sonstiges
5.1.7 Arbeitsgemeinschaften
1.1.1.4 Umgang mit
......
ISNUMERIC()it has some issues. DoesB Kernprozessecan be likeB Kernprozesse1.2.3?ISNUMERICis a bad function, if I'm honest. If you really want to test if a string is a numerical value, useTRY_CONVERTorTRY_CAST.CASEexpression.[name]is clearly avarchar, but your other expression is being cast to anint. As a result[name]is cast to anintas well, due to data type precendence and so the conversion fails.1.1.1.4compare to1.1.2? Right now, your replace turns this into1114 vs 112. Expected output would be helpful.