2016-04-13 40 views
2

我試圖將兩個DateTime參數傳遞給SQL語句。這就是我想用C#代碼一起傳遞:將where類中的DateTime作爲參數傳遞給C#

string command = @"SELECT EMP._name AS employername, EMP._contact AS employercontact, EMP.employerid, EMP.firmid 
       FROM EMPLOYER AS EMP 
       LEFT JOIN SERVICE AS SERV 
       ON EMP.employerid = SERV.employerid 
       WHERE SERV._dateRecordCreated >= @yearStartDate 
       AND SERV._dateRecordCreated <= @yearEndDate 
       ORDER BY employername;"; 

而且這是我想過去的PARAMATERS:

DateTime yearStartDt = new DateTime(2015, 1,1); 
DateTime yearEndDt = new DateTime(2015, 12, 31); 

sqlCommand.Parameters.Add("@yearStartDate", yearStartDt); 
sqlCommand.Parameters.Add("@yearEndDate", yearEndDt); 

我不斷收到SQL異常137

+0

當LEFT JOIN時,將右邊表的條件放在ON子句中以獲得真正的左連接行爲。 (在WHERE中,您會得到常規的內部聯接結果...) – jarlh

+8

刪除SQL中'@ yearStartDate'和'@ yearEndDate'周圍的引號。值不替換 - 不需要字符串引用。 –

+0

我從來沒有通過像這樣的參數,只有這樣:'sqlCommand.Parameters.AddWithValue(「@ yearStartDate」,yearStartDt);' - 基本上說這樣的嘗試,而不是傳遞類型 –

回答

0

使用的東西像這樣

sqlCommand.Parameters.Add("@yearStartDate", SqlDbType.DateTime); 
sqlCommand.Parameters["@yearStartDate"].Value = yearStartDt; 
+4

你應該解釋*爲什麼*這回答了問題 - 'Add'需要一個類型作爲第二個參數,*不是*一個值。它還返回新的SqlParameter對象,所以沒有理由再次用'[「@paramname」]檢索它 –

+2

'sqlCommand.Parameters.Add(「@ yearStartDate」,SqlDbType.DateTime).Value = yearStartDt;' –

相關問題