Linq to SQL Like Operator(×ªÔØ)
As a response for customer's question, I decided to write about using Like Operator in Linq to SQL queries.
Starting from a simple query from Northwind Database;
var query = from c in ctx.Customers
where c.City == "London"
select c;
The query that will be sent to the database will be:
SELECT CustomerID, CompanyName, ...
from dbo.Customers
WHERE City = [London]
There are some ways to write a Linq query that reaults in using Like Operator in the SQL statement:
1. Using String.StartsWith or String.Endswith
Writing the following query:
var query = from c in ctx.Customers
where c.City.StartsWith("Lo")
select c;
will generate this SQL statement:
SELECT CustomerID, CompanyName, ...
from dbo.Customers
WHERE City LIKE [Lo%]
which is exactly what we wanted. Same goes with String.EndsWith.
But, what is we want to query the customer with city name like "L_n%"? (starts with a Capital 'L', than some character, than 'n' and than the rest of the name). Using the query
var query = from c in ctx.Customers
where c.City.StartsWith("L") && c.City.Contains("n")
select c;
generates the statement:
SELECT CustomerID, CompanyName, ...
from dbo.Customers
WHERE City LIKE [L%]
AND City LIKE [%n%]
which is not exactly what we wanted, and a little more complicated as well.
2. Using SqlMethods.Like method
Digging into System.Data.Linq.SqlClient namespace, I found a little helper class called SqlMethods, which can be very usefull in such scenarios. SqlMethods
Ïà¹ØÎĵµ£º
×î½üÐèÒª²âÊÔÒ»¸öÏîÄ¿, ÐèÒªSQL SERVER 2008, ÔÚ΢ÈíÏÂÔØÆÀ¹À°æºó½øÐа²×°
Öм䷢ÏÖÁËÖÖÖÖ°²×°Ê§°ÜµÄÎÊÌ⣬¶Ô¸Ã¹ý³Ì½øÐÐÁ˼Ǽ£¬Ï£Íû¸øÓöµ½´ËÀàÎÊÌâµÄÅóÓÑÃǹ²Í¬Ì½ÌÖ£¬ÓÐËù°ïÖú£º
1. WINDOWS 2003, WINDOWS 7 ÐÂ×°µÄʱºò¿ÉÐУ¬µ«ÊÇÈç¹ûÓÐɾ³ýºóÖØÐ°²×°ÔòÎÞ·¨Ôٴΰ²×°
2. ¸ù¾ÝÍøÉÏÎÞÊýÏÈÇýµÄʧ°ÜÌáʾ£¬ ½øÐÐÁËÎÞÊýÖØÊÔ£¬ ......
--exec [P_AutoGenerateNumber] 'reception_apply','generate_code','',7
/*
¹ý³Ì˵Ã÷:Éú³É×Ô¶¯±àºÅ
´´½¨Ê±¼ä:2010Äê1ÔÂ12ÈÕ
×÷Õß:feng
debug:ÉÐδ¿¼ÂDZàºÅÒç³öÇé¿ö
*/
ALTER proc [P_AutoGenerateNumber]
(
@table ......
µ±SQL Server½Ø¶ÏÊÂÎñÈÕ־ʱ£¬Ëü½ö½öÊÇÔÚÐéÄâÈÕÖ¾ÎļþÖÐ×ö¸ö±ê¼Ç£¬ÒԱ㲻ÔÙʹÓÃËü£¬È»ºó×¼±¸ÒÔÖØÓÃÐÎʽÀ´×ö±¸·Ý(¼ÙÈçÔËÔØÔÚÍêÕû»òÊÇÅúÁ¿ÈÕÖ¾»Ö¸´Ä£ÐÍ)¡£Ò²¾ÍÊÇ˵£¬ÔÚʹÓüòµ¥»Ö¸´Ä£ÐÍʱ£¬ÊÂÎñÈÕÖ¾°üÀ¨ÈçϵÄÈÕÖ¾¼Ç¼£º
µ±checkpoint·¢Éúʱ£¬ÐéÄâÈÕÖ¾Îļþ1¡¢2²»ÔÙ±»Ê¹Óã¬ÒòΪÊÂÎñ1¡¢2ÒѾ±»Ìá½»ÁË£¬¶øÇÒÈÕÖ¾¼Ç¼Ҳ²»ÔÙÐ ......
ms sqlÖеÄintÐÍĬÈÏÊÇ4룬mysqlµÄintÐÍĬÈÏÊÇ11λ£¬Ç°Õßµ½ºóÕßµÄÒÆÖ²²»»áÓÐʲôÒþ»¼£¬µ«ÊǺóÕßµ½Ç°ÕßµÄÒÆÖ²¾Í´æÔÚλÊý²»¹»£¬²»ÄÜ´æ´¢´óÊýµÄÒþ»¼¡£
»¹ÓÐbigint£¬ms sqlÊÇ8룬mysqlĬÈÏÊÇ20λ¡£ ......