我有3个表:users
,feed(id,body,title,link)
和userstofeed(id,userid,feedid,isread)
,而我尝试从userstofeed表读取bool值时会带来IndexOutOfRangeException
。告诉我我在做什么错
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;
}
而这里的SQL存储过程:
create proc spGetItemsByUser
@userName nvarchar(50)
as
begin
declare @userId int
declare @feedId table (id int)
select @userId = id
from Users
where name = @userName
insert into @feedid (id)
select feedid, isread
from userstofeed
where userid = @userId
select * from feed where id in (select id from @feedId)
select isread from userstofeed where userid = @userId //Here I'm getting bit if it read or not
end
最佳答案
将存储过程中的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
值作为行附加在title
,feed
和body
的行之后。正如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
关于c# - IndexOutOfRangeException SqlDataReader从表中读取 bool 值,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/36175489/