2017-05-18 54 views
0

我在我的程序中有一段代碼,它應該在特定事件中提取最近一批的時間。然而我所得到的卻是一個空白的結果。我知道表中有相關​​數據,SQL Profiler顯示它正在執行。C#SQL查詢不產生數據

public void UpdateBeginStir() 
    { 
     string beginStir = null; 
     string connectionString = "(Omitted)"; 
     string commandLine = "SELECT MAX(Event_Time) AS Time " + 
          "FROM dbo.Custom_EventLog " + 
          "WHERE Container_ID = @LOTNUMBR " + 
          "AND Event_ID = 1 " + 
          "GROUP BY BadgeNo, Container_ID, Event_ID"; 
     using (SqlConnection connection = new SqlConnection(connectionString)) 
     { 
      connection.Open(); 
      using (SqlCommand command = new SqlCommand(commandLine, connection)) 
      { 
       command.Parameters.Add("@LOTNUMBR", SqlDbType.NChar, 50).Value = TextBoxLot.Text; 
       SqlDataReader reader = command.ExecuteReader(); 
       while (reader.Read()) 
       { 
        beginStir = reader["Time"] as string; 
        break; 
       } 
      } 
      connection.Close(); 
     } 
     MessageBox.Show(beginStir, "test", MessageBoxButton.OK); 
     LabelBeginStir.Content = beginStir; 
    } 
+1

如果執行從SSMS查詢,它返回的結果? –

+0

所以當你執行 「SELECT MAX(EVENT_TIME)隨着時間的 FROM dbo.Custom_EventLog WHERE CONTAINER_ID = '無論LOTNUMBR是' 和事項標識= 1 GROUP BY BadgeNo,CONTAINER_ID,事項標識」,它給了預期的結果? TextBoxLot.Text的價值是什麼? –

+0

當我在SSMS中執行查詢時,會得到最近一次的預期結果。當我在代碼中運行它時,由於消息框爲空,我得到一個空白結果。 –

回答

4

SqlDbType.NChar將填充空格最多50個字符,並且Container_ID不匹配。使用SqlDbType.NVarChar代替

UPDATE:正確答案最終被

beginStir = Convert.ToDateTime(reader["Time"]).ToString(); 
+1

好的,如果這是原因,那太棒了! @Ryan Fauser。但是不應該把'LOTNUMBR'作爲'int'還是至少是一個'數字'?假設'Container_ID'是一個int。 –

+1

@WEI_DBA偉大的一點。另外,Filburt提出了一個有效的觀點。此代碼中有幾件事情需要改進。 –

+0

我在Convert.ToInt32行上得到「System.FormatException:'輸入字符串格式不正確''。我在程序的其他部分查詢批號,它工作得很好。它可能是我如何進入Event_ID的東西? –