【发布时间】:2018-07-18 22:04:02
【问题描述】:
我创建了以下导致错误状态的序列
System.IndexOutOfRangeException: '索引超出了数组的范围。'
如 cmets 所示。
SqlCommand cmd = new SqlCommand(@"SELECT GETDATE() 'Today', DATENAME(weekday, GETDATE()) 'Day Name';
select * from [Schedule] where Working = datename(weekday,GetDate()) and Commencing != Finishing;
select * from [Vacation] where VacStart = GetDate();", con);
con.Open();
SqlDataReader read = cmd.ExecuteReader();
DateTime now = DateTime.Today;
while (read.Read())
{
// from Schedule Table
string Working = read.GetString(1);
DateTime Commencing = read.GetDateTime(2); //Exception Error Here
DateTime Finishing = read.GetDateTime(3); //Exception Error Here
// from Vacation Table
string Reason = read.GetString(1);
if (Reason == null)
{
// if condition is met
lblMsg2.Text = "<p class='closed'>Sorry, we are closed for for a personal holiday.<br />If you are a current client and this is an emergency, we will of course make every effort to accommodate you.</p>";
}
else
{
// if condition is not met
if (Working != null && now >= Commencing && Finishing <= now)
{
// if condition met
lblMsg2.Text = "<p class='open'>Yes, we are currently open and would love to hear from you!</p>";
}
else
{
// if condition is not met
lblMsg2.Text = "<p class='closed'>Sorry, we are currently closed. You can reach us during normal business hours. We would love to have the opportunity to speak with you!</p>";
}
}
}
根据我对大量帖子的研究,我认为错误是由日期差异引起的,即 1900-01-01 与 2018-07-18。日期不相关,因为我只是想比较时间。
我尝试了几种变体,您可以在其中更改查询以考虑日期,但我无法让这些工作。
看起来每个人都将数据从 DateTime 转换为字符串,我也很难开始工作。
Commencing 和 Finishing 列在 SQL Server 数据库中都是 DateTime 类型。
【问题讨论】:
-
您已经编写了三个 SELECT 命令。读取器在完成读取第一个 SELECT 的结果之前不能使用第二个 SELECT 的结果。第一个选择中没有第三个字段,第二个选择也是如此。
-
mjwills, cmets 是我的笔记,这样我就可以记住数据与哪些表相关联,即 Working、Starting 和 Finishing 都是 Schedule 表中的表,等等。这就是全部意思由那些。
-
谢谢史蒂夫!这有帮助。我删除了第一个选择查询,列出了我想读取的字段,以便剩余的两个选择都提取相同数量的结果列。它现在可以按我的意愿工作,并且消息正在发布。
-
尝试删除 dataReader 并使用 DataAdapter:docs.microsoft.com/en-us/dotnet/framework/data/adonet/… 然后您可以使用诸如 Commencing = Table[1] & Finishing = Table [2] 之类的东西 - 即使这两个表只包含一条记录
标签: c# sql-server exception