Like Predicate on INT

Posts   
 
    
Posts: 94
Joined: 23-Aug-2006
# Posted on: 12-Jul-2013 18:54:55   

We have a requirement to enable LIKE predicate (wildcard) searches on a field that is based on an INT datatype. All examples in the help are based on STRING data types,which makes sense since that's where its mostly applied. Can you tell me how I can implement a LIKE search against an INT? Its the equivalent of the following sql stmt SELECT * FROM Orders WHERE OrderID Like '11%'

arschr
User
Posts: 893
Joined: 14-Dec-2003
# Posted on: 12-Jul-2013 19:16:12   

Once you get an answer from support I would still be careful, and making sure performance and results are what you want.

From the SqlServer docs on Like

If any one of the arguments is not of character string data type, the SQL Server Database Engine converts it to character string data type, if it is possible.

To me this sounds like you may end up doing a table scan as the engine will have to convert each rows value to a string before it can evaluate whether it is like x or not.

daelmo avatar
daelmo
Support Team
Posts: 8245
Joined: 28-Nov-2005
# Posted on: 13-Jul-2013 08:06:05   

I didn't know that you can do that with "LIKE". Apparently it's supported out of the box on LLBLGen. See this:

var orders = new EntityCollection<OrderEntity>();

var filter = new RelationPredicateBucket();
filter.PredicateExpression.Add(OrderFields.OrderId %  "1025%");

using (var adapter = new DataAccessAdapter())
{
    adapter.FetchEntityCollection(orders, filter);
}

It actually compiles and generates this SQL:

SELECT [Northwind].[dbo].[Orders].[CustomerID] AS [CustomerId],
       ...
FROM   [Northwind].[dbo].[Orders]
WHERE  ([Northwind].[dbo].[Orders].[OrderID] LIKE @p1) 
@p1 is "1025%"

SQL Profiler reported this executed SQL:

exec sp_executesql N'SELECT [Northwind].[dbo].[Orders].[CustomerID] AS [CustomerId], 
... 
FROM [Northwind].[dbo].[Orders]   
WHERE ( [Northwind].[dbo].[Orders].[OrderID] LIKE @p1)',N'@p1 nvarchar(5)',@p1=N'1025%'

So, just use it like that. BTW, the warning posted by Al is also a good point you should consider.

David Elizondo | LLBLGen Support Team
Otis avatar
Otis
LLBLGen Pro Team
Posts: 39614
Joined: 17-Aug-2003
# Posted on: 13-Jul-2013 10:29:39   

To speed this up, you could opt for adding a second field, which you fill with the string variant of the int you're searching for, and add an index on that. You then use the predicate on that field. You could use a calculated field for this in the table (using a cast(intfield)). This should use the index.

Frans Bouma | Lead developer LLBLGen Pro
Posts: 94
Joined: 23-Aug-2006
# Posted on: 15-Jul-2013 20:00:38   

Thanks everyone for the very useful information ! Appreciate it.