I need to find the highest value from the database that satisfies a certain formatting convention. Specifically, I would like to find the highest value that looks like
EU999999 ('9' being any digit)
select max(col) will return something like 'EUZ...' for instance that I want to exclude. The following query does the trick, but I can't produce this via Linq-to-SQL. There seems to be no translation for the isnumeric() function in SQL Server.
select max(col) from table where col like 'EU%'
and 1=isnumeric(replace(col, 'EU', ''))
Writing a database function, stored procedure, or anything else of that nature is far down the list of my preferred solutions, because this table is central to my app and I cannot easily replace the table object with something else.
What's the next-best solution?
As you said, there is no translation for IsNumeric from LINQ to SQL. There are a few options, you already wrote database function and stored procedure down. I like to add two more.
Option 1: You can do this by mixing LINQ to SQL with LINQ to Objects, but when you've got a big database, don't expect great performance:
Option 2: change your database schema :-)
Although
ISNUMERIC
is missing, you could always try the nearly equivalentNOT LIKE '%[^0-9]%
, i.e., there is no non-digit in the string, or alternatively, the string is empty or consists only of digits:Of course, if you know that the number of digits is fixed, this can be simplified to
My suggestion is to fall back to in-line SQL and use the DataContext.ExecuteQuery() method. You would use the SQL query you posted in the beginning.
This is what I have done in similar situations. Not ideal, granted, due to the lack of the type-checking and possible syntax errors, but simply make sure it is included in any unit tests. Not every possible query is covered by the Linq syntax, hence the existence of ExecuteQuery in the first place.
You could make use of the
ISNUMERIC
function by adding a method to a partial class for the DataContext. It would be similar to using a UDF.In your DataContext's partial class add this:
Then your code would use it in this manner:
Or you could make use MAX:
Depending on your final goal it might be possible to stop at the
max
variable and prepend it with the "EU" text to avoid the 2nd query that gets the column name.EDIT: as mentioned in the comments, the shortcoming of this approach is that ordering is done on text rather than numeric values and there's currently no translation for
Int32.Parse
on SQL.