2013-02-01 24 views
0

我具有用於從LINQ從多個表中搜索作爲執行查詢模式錯誤的同時從LINQ retriving數據到SQL

`ALTER PROCEDURE [dbo].[rdsp_Srchfld] 
(
@strFldlst as nvarchar(max), 
@strTblnm as nvarchar(max), 
@intSrchStyle as int, 
@strcond1 as nvarchar(250), 
@strCond2 as nvarchar(250)=null, 
@strCond3 as nvarchar(300) 
) 
AS 
BEGIN 
declare @strSql as varchar(7000) 


--Process 
set @strSql = 'select Distinct ' + @strFldlst + ' from ' + @strTblnm 
IF @intSrchStyle = 0 
BEGIN 
    SET @strSql = @strSql + ' where ' + @strcond1 + ' = ' + '''' + @strCond2 + '''' + ' order by ' + '' + @strcond3 + '' 
END 
ELSE IF @intSrchStyle = 1 
BEGIN 
    SET @strSql = @strSql + ' where ' + @strcond1 + ' like ' + '''' + @strCond2 + '%' + '''' + ' order by ' + '' + @strcond3 + '' 
END 



ELSE IF @intSrchStyle = 2 
BEGIN 
    SET @strSql = @strSql + ' where ' + @strcond1 + ' like ' + '''' + '%' + @strCond2 + '%' + '''' + ' order by ' + '' + @strcond3 + '' 
END 

EXEC (@strSql) 
END` 

和傳遞參數到SQL作爲

var rslt = from srch in custDC.rdsp_Srchfld(fldName, tblName, srchType, cond1, cond2, cond3) select srch; 

存儲過程現在我試圖建立我的程序,我得到的錯誤爲

Error 1 Could not find an implementation of the query pattern for source type 'int'. 'Select' not found. 

爲什麼我得到錯誤a我該如何執行它。

+0

當您使用Linq-To-Sql時,爲什麼要在SP中使用動態SQL?這種方法結合了SP的所有危險和不靈活性,同時避免了任何好處。如果使用得當,出於正確的原因,他們可以快速而安全。 – Jodrell

+0

可以爲此SP編譯什麼查詢計劃? – Jodrell

+0

@Jodrell:通過傳遞表名和字段名作爲參數從多個表中檢索數據。 –

回答

2

不要這樣做。現在放棄你的方法。

開始通過閱讀此,http://www.sommarskog.se/dynamic_sql.html

想想爲什麼LINQ到SQL創建。看看它的繼任者EF。

然後從支持ORM的已建立的SQL Server爲數據庫建立模型。然後使用該模型爲您提供很好的類型檢查代碼。讓模型爲你做dymanic SQL。如果您有特殊要求或ORM無法應對的情況。然後考慮寫一個特殊的SP來處理它。


如果您要堅持使用您的方法至少了解SQL Injection attack是什麼。瞭解有關sp_executesql並使用它。


如果LINQ到SQL不能得到您的動態SQL的權利,不管出於什麼原因,它更有意義來構建客戶/應用層上的聲明,而不是在一個SP。請看的ExecuteQueryExecuteCommand方法。如果ORM太多,使用vanilla ADO.Net和SqlCommand有優點。

+0

Linq2SQL演變成EF是一個相當強大的說法。 – leppie

+0

@leppie,真的,自然選擇永不止步。 – Jodrell