C#SQL查询不生成数据

时间:2017-05-18 16:35:24

标签: c# sql sql-server

我的程序中有一段代码,可以在特定事件中为批处理提取最近的时间。然而,所有我得到的结果都是空白。我知道该表中有关于该批处理的数据,SQL Profiler显示它正在执行。

 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 个答案:

答案 0 :(得分:4)

SqlDbType.NChar将向右填充最多50个字符的空格,而Container_ID将不匹配。请改用SqlDbType.NVarChar

更新:正确答案最终成为

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