简体   繁体   English

从asp.net中的存储过程返回一行

[英]Return one row from stored procedure in asp.net

I one to create a stored procedure to retrieve one row in the table: 我创建一个存储过程来检索表中的一行:

create procedure LogInUser
    @username nvarchar(64),
    @password nvarchar(64),
    @succeed bit out,   
    @not_exist_err bit out
as
declare @exist_user nvarchar(64)
select @exist_user = username from users
where username = @username

if @exist_user is null
begin
    set @succeed = 0
    set @not_exist_err = 1
    return
end
else
begin
    select * from users
    where username = @username and password = @password 
end
return

First, I verify if a user exist or not by using: 首先,通过使用以下命令验证用户是否存在:

select @exist_user = username from users
where username = @username

Then get the row with every column: 然后获取每一列的行:

select * from users
where username = @username and password = @password 

However, by using SqlDataReader , the program won't enter the while loop to retrieve the information. 但是,通过使用SqlDataReader ,程序将不会进入while循环以检索信息。

It just don't enter the loop. 它只是不进入循环。 I don't understand why, even I executed it using SQL Server like this, it did return a row: 我不明白为什么,即使使用这样的SQL Server执行它,它也确实返回了一行:

declare @succeedResult bit
declare @existErr bit
exec LogInUser @username=admin, @password =admin, @succeed = @succeedResult, @not_exist_err = @existErr

EDIT : The C# method which executes the store procedure: 编辑 :执行存储过程的C#方法:

public User LogIn(User usr)
{
   SqlConnection conn = A2.Controller.Utils.conn;
   SqlCommand loginCmd = new SqlCommand("LogInUser", conn);
   loginCmd.CommandType = CommandType.StoredProcedure;

   User result = new User();

   try
   {
       conn.Open();
       loginCmd.Parameters.Add("@username", SqlDbType.NVarChar).Value = usr.Username;
       loginCmd.Parameters.Add("@password", SqlDbType.NVarChar).Value = usr.Password;
       loginCmd.Parameters.Add("@succeed", SqlDbType.Bit).Direction = ParameterDirection.Output;
       loginCmd.Parameters.Add("@not_exist_err", SqlDbType.Bit).Direction = ParameterDirection.Output;                
       SqlDataReader dr = loginCmd.ExecuteReader();              

       if (loginCmd.Parameters["@succeed"].Value != DBNull.Value){
          Console.WriteLine("User does not exist");
          SqlParameter notExistErr = loginCmd.Parameters["@not_exist_err"];

          if (notExistErr.Value != DBNull.Value){
             throw new NotExistException("The username or password is incorrect.", "Users");
          }
       }

       while (dr.Read()) {
           Console.WriteLine("Looping dr");
           result.Username = (string) dr["username"];
           result.Password = (string) dr["password"];
           result.FirstName = (string) dr["first_name"];
           result.MiddleName = (string) dr["middle_name"];
           result.LastName = (string) dr["last_name"];
           result.ManagerID = (int) dr["manager_id"];
           result.IsAdmin = (int) dr["is_admin"];

           return result;
        }
        Console.WriteLine("Done reading");
    }             
    finally {
       if (conn.State == ConnectionState.Open) conn.Close();
    }
    return result;
 }

Output parameters are only filled after you read the last row from the last result set in the procedure. 仅在您从过程中的最后一个结果集中读取了最后一行后,才填充输出参数。 So this part won't work: 因此,这部分将不起作用:

SqlDataReader dr = loginCmd.ExecuteReader();              
if (loginCmd.Parameters["@succeed"].Value != DBNull.Value){

At this point loginCmd.Parameters["@succeed"].Value is not set: it will be set only after you've read the last row, and dr.Read() has returned false . 此时,未设置loginCmd.Parameters["@succeed"].Value :只有在您读完最后一行并且dr.Read()返回false之后,才会设置该值。

As a best practice, don't use output parameters in stored procedures that return rowsets. 最佳做法是,不要在返回行集的存储过程中使用output参数。

You can check whether your query returns the result or is not using dr.HasRows , and it should look like... 您可以检查查询是否返回结果,或者不使用dr.HasRows ,它应该看起来像...

SqlDataReader dr = loginCmd.ExecuteReader();              
if (!dr.HasRows)
{
    Console.WriteLine("User does not exist");
    SqlParameter notExistErr = loginCmd.Parameters["@not_exist_err"];
    if (notExistErr.Value != DBNull.Value)
    {
        throw new NotExistException("The username or password is incorrect.", "Users");
    }
}
else
{
    while (dr.Read())
    {
        Console.WriteLine("Looping dr");
        result.Username = (string) dr["@username"];
        result.Password = (string) dr["@password"];
        result.FirstName = (string) dr["@first_name"];
        result.MiddleName = (string) dr["@middle_name"];
        result.LastName = (string) dr["@last_name"];
        result.ManagerID = (int) dr["@manager_id"];
        result.IsAdmin = (int) dr["@is_admin"];
        return result;
    }
}

Something is strange -- I would expect your test to look like this: 有点奇怪-我希望您的测试看起来像这样:

declare @succeedResult bit
declare @existErr bit
exec LogInUser @username=N'admin', @password =N'admin', @succeed = @succeedResult, @not_exist_err = @existErr

But this brings up the simple answer.... are you calling your function with valid (ie exist) for username AND password? 但是,这引出了一个简单的答案。...您是否使用有效(即存在)的用户名和密码来调用函数?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 Asp.net MVC 3存储过程从表中返回一个值 - Asp.net MVC 3 stored procedure to return one value from the table 从asp.net中的存储过程中获取返回值 - Get Return Value from Stored procedure in asp.net ASP.NET SQL Server存储过程返回Message - ASP.NET SQL Server stored procedure return Message 将多行返回到ASP.NET MVC应用程序的存储过程 - Stored procedure to return multiples rows to ASP.NET MVC application 从存储过程中获取C#asp.net中的返回值(语法问题) - Getting a Return Value in C# asp.net from a stored procedure (syntax issue) ASP.NET MVC4从带有实体框架的存储过程返回输出 - ASP.NET MVC4 return output from a stored procedure with Entity Framework C# & ASP.NET MVC 5 - 从按钮单击执行存储过程,没有返回值 - C# & ASP.NET MVC 5 - execute stored procedure from button click with no return values 存储过程的返回值仅在 ASP.NET 中获取第一个字符 - The return value from a stored procedure gets the first character only in ASP.NET 如何使用asp.net读取没有参数的存储过程返回的日期? - How to read the date that is return from a stored procedure which have no parameter using asp.net? 从每个INSERT上的存储过程返回受影响的行,以在ASP.NET页面中显示 - Return rows affected from a Stored Procedure on each INSERT to display in ASP.NET page
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM