【发布时间】:2014-08-08 18:04:19
【问题描述】:
所以我有一个相对简单的查询,但它与 full_name 文本字段不匹配,即使我可以看到数据在那里并且完全匹配?
我确保检查传入的fullName 参数是正确的值。我找不到任何文档来验证我是否需要单引号,但没有它就会引发错误。
大家有什么建议吗?
SQL 语句有问题的代码?
public static ObservableCollection<ShiftView> GetShifts(DateTime? start, DateTime? stop, string fullName, bool? closed)
{
ObservableCollection<ShiftView> shifts = new ObservableCollection<ShiftView>();
// INFO: Not intended to retrieve a lot of records as there is no caching....
OleDbCommand cmd = new OleDbCommand("SELECT profiles.profile_id, profiles.full_name, shifts.start, shifts.stop, shifts.start_log, shifts.stop_log, shifts.start_notes, shifts.stop_notes FROM shifts, profiles WHERE " +
(start.HasValue ? "(shifts.start>=@start) AND " : "") +
(stop.HasValue ? "(shifts.stop<=@stop) AND " : "") +
(fullName != null ? "profile.full_name='@full_name' AND " : "") +
(closed.HasValue ? "shifts.closed=@closed AND " : "") +
"(shifts.profile_id=profiles.profile_id)"
);
if (start.HasValue)
cmd.Parameters.AddWithValue("@start", start.Value.ToString());
if (stop.HasValue)
cmd.Parameters.AddWithValue("@stop", stop.Value.ToString());
if (fullName != null)
cmd.Parameters.AddWithValue("@full_name", fullName);
if (closed.HasValue)
cmd.Parameters.AddWithValue("@closed", closed);
OleDbDataReader reader = Database.Read(cmd);
DateTime? _stop, _stopLog;
while(reader.Read())
{
Console.WriteLine("!");
// shorthand form if's with ? does not work here.
if (reader.IsDBNull(reader.GetOrdinal("stop")))
_stop = null;
else
_stop = reader.GetDateTime(reader.GetOrdinal("stop"));
if (reader.IsDBNull(reader.GetOrdinal("stop_log")))
_stopLog = null;
else
_stopLog = reader.GetDateTime(reader.GetOrdinal("stop_log"));
shifts.Add(new ShiftView(
reader.GetString(reader.GetOrdinal("profile_id")),
reader.GetString(reader.GetOrdinal("full_name")),
reader.GetDateTime(reader.GetOrdinal("start")),
_stop,
reader.GetDateTime(reader.GetOrdinal("start_log")),
_stopLog,
reader.GetString(reader.GetOrdinal("start_notes")),
reader.GetString(reader.GetOrdinal("stop_notes"))
));
}
return shifts;
}
上面的代码通过这个按钮被调用:
private void ShowStatsButton_Click(object sender, RoutedEventArgs e)
{
DateTime? start = StartDatePicker.SelectedDate;
DateTime? stop = StopDatePicker.SelectedDate;
string name = NameComboBox.Text;
if (name.Equals("Everyone"))
name = null;
if (stop.HasValue)
stop = stop.Value.AddDays(1);
StatsGridView.ItemsSource = Shift.GetShifts(start, stop, name, true);
}
这会过滤日期范围以及是否有全名。我确保 name 的值有效。
【问题讨论】: