程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> C語言 >> 關於C語言 >> C# 3.0入門系列(十一)-之In, Like操作(3)

C# 3.0入門系列(十一)-之In, Like操作(3)

編輯:關於C語言

再比如:

var q = (from c in db.Customers
where SqlMethods.Like(c.CustomerID, "ARO%")
select c).ToList();

SqlMethods.Like最奇妙的地方,莫過於,自己定義的通配表達式,你可以在任何地方實現通配。比如

var q = (from c in db.Customers

where SqlMethods.Like(c.CustomerID, "A%O%T")

select c).ToList();

其生成的sql為

SELECT [t0].[CustomerID], [t0].[CompanyName], [t0].[ContactName], [t0].[ContactT
itle], [t0].[Address], [t0].[City], [t0].[Region], [t0].[PostalCode], [t0].[Coun
try], [t0].[Phone], [t0].[Fax]
FROM [dbo].[Customers] AS [t0]
WHERE [t0].[CustomerID] LIKE @p0
-- @p0: Input String (Size = 5; Prec = 0; Scale = 0) [A%O%T]

就是最標准的知道以A開頭,以T結尾,中間知道一個值O,其他就什麼不知道了。就用這個。

SQL Server 定義了四種通配符,在這裡都可以使用。它們是:

Wildcard character Description Example % Any string of zero or more characters. WHERE title LIKE '%computer%' finds all book titles with the Word 'computer' anywhere in the book title. _ (underscore) Any single character. WHERE au_fname LIKE '_ean' finds all four-letter first names that end with ean (Dean, Sean, and so on). [ ] Any single character within the specifIEd range ([a-f]) or set ([abcdef]). WHERE au_lname LIKE '[C-P]arsen' finds author last names ending with arsen and beginning with any single character between C and P, for example Carsen, Larsen, Karsen, and so on. [^] Any single character not within the specifIEd range ([^a-f]) or set ([^abcdef]). WHERE au_lname LIKE 'de[^l]%' all author last names beginning with de and where the following letter is not l.%表示零長度或任意長度的字符串。_表示一個字符。[]表示在某范圍區間的一個字符。[^]表示不在某范圍區間的一個字符

比如:

var q = (from c in db.Customers
where SqlMethods.Like(c.CustomerID, "A_O_T")
select c).ToList();

就用_代表一個字符。其生成sql為

SELECT [t0].[CustomerID], [t0].[CompanyName], [t0].[ContactName], [t0].[ContactT
itle], [t0].[Address], [t0].[City], [t0].[Region], [t0].[PostalCode], [t0].[Coun
try], [t0].[Phone], [t0].[Fax]
FROM [dbo].[Customers] AS [t0]
WHERE [t0].[CustomerID] LIKE @p0
-- @p0: Input String (Size = 5; Prec = 0; Scale = 0) [A_O_T]

對於Not Like,也很簡單,加個取非就是。

var q = (from c in db.Customers
where !SqlMethods.Like(c.CustomerID, "A_O_T")
select c).ToList();

SqlMethods.Like還有一個參數,叫escape Character,其將會被翻譯成類似下面的語句。

SELECT columns FROM table WHERE
column LIKE '%\%%' ESCAPE '\'

escape 是因為某字段中含有特殊字符,比如%,_ [ ]這些被用作通配符的。這時就要用到Escape了。這是SQL Server的事情了。詳細情況請參考:

http://msdn2.microsoft.com/en-us/library/Aa933232(SQL.80).ASPx

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved