2010-05-04 48 views
1

我有一个查询:SqlDataReader对象和行数

declare @Code nvarchar(100) 
select @Code="BMW" 
select name from NewCars where [email protected] 
if @@rowcount = 0 
Select name from OldCars where [email protected] 

在SQL同治工作室第一部分给我0 resuklts,和第二1一个结果,那是好的,但 在SqlDataReader的我用的是相同的查询ofcource无:

declare @Code nvarchar(100) 
select @Code="BMW" 

,因为我使用:

cmd.Parameters.AddWithValue("@Code", "BMW"); 

而且

using (SqlDataReader reader = cmd.ExecuteReader()) 
        { 
         if (reader.HasRows) 
         { 
          while (reader.Read()) 
          { 
           Name= reader["Name"].ToString(); 
          } 
         } 
         else 
         { 
          throw new NotSupportedException("Lack of car with this Code"); 
         } 
        } 

给了我零结果

回答

3

数据库结果多个结果,所以如果第一个结果是空的,你需要使用reader.NextResult()就移动到第二个结果。

您也可以查询通过检查返回一个结果,如果第一个选择将包含什么:

declare @Code nvarchar(100) 
select @Code="BMW" 
if (exists(select * from NewCars where [email protected])) begin 
    select name from NewCars where [email protected] 
end else begin 
    select name from OldCars where [email protected] 
end