IndexOutOfRangeException SqlDataReader从表中读取bool值

时间:2016-03-23 10:24:16

标签: c# sql sql-server stored-procedures sqldatareader

我有3个表格:usersfeed(id,body,title,link)userstofeed(id,userid,feedid,isread),而我正在尝试从带来{* 1}}的userstofee表中读取bool值。请告诉我,我做错了什么

IndexOutOfRangeException

这里是sql store程序:

while (reader.Read())
{
     rssFeed.Title = reader["title"].ToString();
     rssFeed.Body = reader["body"].ToString();
     rssFeed.Link = reader["link"].ToString();
     rssFeed.IsRead = (bool) reader["isread"]; //IndexOutOfRangeException here
     yield return rssFeed;
}

1 个答案:

答案 0 :(得分:6)

将存储过程中的SELECT更改为:

SELECT [feed].[title], [feed].[body], [feed].[link], [userstofeed].[isread]
FROM [feed]
INNER JOIN [userstofeed] ON ([userstofeed].userid = @userId)
WHERE [feed].[id] in (select id from @feedId)

我认为您的版本isread不是第一个结果集的列。 isread值被追加为titlefeedbody行之后的行。

正如Zohar Peled建议的那样,我尝试对整个存储过程进行重构:

CREATE PROC spGetItemsByUser
   @userName nvarchar(50)
AS
BEGIN
    SELECT [feed].[title], [feed].[body], [feed].[link], [userstofeed].[isread]
    FROM [feed]
    INNER JOIN [userstofeed] ON ([userstofeed].[feedid] = [feed].[id])
    INNER JOIN [users] ON ([users].[id] = [userstofeed].[userid])
    WHERE [users].[name] = @userName
END