2016-10-20 112 views
0

我無法手動將CurrentSystemTime添加到我的查詢中。查詢存儲在一個字符串變量中。但concationation部分給錯誤:使用DateTime字符串查詢的Concat字符串

查詢是:

string myQuery= @"SELECT MAX(ASD.eventDateTime) AS second, R.resourceID,R.resourceLoginID,ASD.agentID 
        FROM AgentStateDetail AS ASD INNER JOIN 
        Resource AS R ON ASD.agentID = R.ResourceID WHERE ASD.eventDateTime >='" + DateTime.Today.ToString("yyyy-MM-dd h:mm:ss") + "'AND ASD.eventDateTime <='2016-10-18 23:59:59' 
        GROUP BY R.ResourceID,R.resourceLoginID,ASD.agentID" 

The Problem part is:

WHERE ASD.eventDateTime >='" + DateTime.Today.ToString("yyyy-MM-dd h:mm:ss") + "'

Error is:

Represent Text as unicode character Newline in constant.

+0

「模型 - 視圖控制器」標籤用於模式從用戶界面(輸入和顯示)隔離「域邏輯」(用戶的應用程序邏輯),允許獨立開發,測試和維護每個(分離的擔憂)。不適用於SQL查詢。 –

+0

你應該看看準備好的語句,因爲這很容易受到SQL注入的影響,它也會提高性能並且是最先進的。 – Andre

+1

@Andre:實際上,在這種情況下,查詢不容易受到SQL注入攻擊,因爲日期時間的格式化結果是固定的。 – Georg

回答

4

你忘了用@這是開始字符串的第二部分,爲什麼編譯修訂的新行字符無效:

string myQuery= @"SELECT MAX(ASD.eventDateTime) AS second, R.resourceID,R.resourceLoginID,ASD.agentID 
        FROM AgentStateDetail AS ASD INNER JOIN 
        Resource AS R ON ASD.agentID = R.ResourceID WHERE ASD.eventDateTime >='" + DateTime.Today.ToString("yyyy-MM-dd h:mm:ss") + @"'AND ASD.eventDateTime <='2016-10-18 23:59:59' 
        GROUP BY R.ResourceID,R.resourceLoginID,ASD.agentID" 
+0

第二次添加@仍將字符串視爲1個字符串對象嗎? –

+0

@BASEERULHASSAN您將三個字符串連接成一個。對於編譯器來說,每一個都是單獨處理的,但是串聯會將它們組合成一個對象。 – Georg

+0

謝謝Maestro。 –

1

您可以使用參數化查詢如下,

string sql = "SELECT MAX(ASD.eventDateTime) AS second, R.resourceID, R.resourceLoginID, ASD.agentID FROM AgentStateDetail AS ASD INNER JOIN Resource AS R ON ASD.agentID = R.ResourceID WHERE ASD.eventDateTime >= @dateTimeStart AND ASD.eventDateTime <= @dateTimeEnd GROUP BY R.ResourceID,R.resourceLoginID,ASD.agentID"; 

using (SqlConnection connection = new SqlConnection(/* connection info */)) 
using (SqlCommand command = new SqlCommand(sql, connection)) 
{ 
    var dateTimeStart = new SqlParameter("dateTimeStart", SqlDbType.DateTime); 
    dateTimeStart.Value = new DateTime("yyyy-MM-dd h:mm:ss"); 

    var dateTimeEnd = new SqlParameter("dateTimeEnd", SqlDbType.DateTime); 
    dateTimeEnd.Value = new DateTime("yyyy-MM-dd h:mm:ss"); 

    command.Parameters.Add(dateTimeStart); 
    command.Parameters.Add(dateTimeEnd); 
    var results = command.ExecuteReader(); 
}