在LINQ中,可以利用延遲執行在設計時分離彼此的不同關注點。我的提供程序將生成一個最佳的SQL語句來獲取數據。請看下面的例子:LINQ在T-SQL中推遲執行的等效代碼
// some complex query to fetch matches goes here
IEnumerable<Match> data = null;
if (/* some condition */)
{
data = from m in Context.Matches
where /* ... */
select m;
}
else
{
data = from m in Context.Matches
join /* .. */
join /* .. */
where /* ... */
select m;
}
// later on, order the data depending on some user selection
IOrderedEnumerable<Match> orderedData = null;
switch (someOption)
{
case /*...*/:
orderedData = from m in data orderby by m.Start select m;
break;
case /*...*/
orderedData = from m in data orderby by m.ID select m;
break;
}
// do something with the computed data
是否有一個有效的方式來實現在存儲過程中相同的功能,而不需要構建查詢作爲一個字符串?我所能想到的只是表變量,但我不知道它們對性能的影響:
CREATE @matches TABLE
(
ID int,
-- ...
Start datetime
)
-- some complex query to fetch matches goes here
IF -- some condition
INSERT INTO @matches(ID, Start)
SELECT ID, ..., Start FROM Matches WHERE ...
ELSE
INSERT INTO @matches(ID, Start)
SELECT ID, ..., Start FROM Matches JOIN ... JOIN ... WHERE ...
-- later on, order the data depending on some user selection
CREATE @orderedMatches TABLE
(
ID int,
-- ...
Start datetime
)
IF -- some option
INSERT INTO @orderedMatches (ID, Start)
SELECT ID, ..., Start FROM @matches ORDER BY Start ASC
ELSE IF -- some option
INSERT INTO @orderedMatches (ID, Start)
SELECT ID, ..., Start FROM @matches ORDER BY ID ASC
-- do something with the computed data
我想你在談論視圖和表值函數。正如@馬丁史密斯所說,CTE最接近lambda的概念。 – Jodrell