将参数传递给SQL Server存储过程

kam*_*ani 1 c# sql-server

我试图将参数传递给我的应用程序中的存储过程,但我不知道我做错了什么.我收到一个错误

过程或函数'usp_getBorrowerDetails'需要参数'@BookID',这是未提供的.

虽然我正在路过,但我做了很多事情,但仍未找到解决办法.

这是我的代码:

IDataReader reader = null;

SqlCommand command = new SqlCommand();

try
{
    SqlConnection connection = GetDBConnection();

    command.CommandType = CommandType.StoredProcedure;
    command.CommandText = Constants.SP_BookBorrowerDetails;
    command = new SqlCommand(command.CommandText, connection);

    command.Parameters.AddWithValue("@BookID", bookID);

    reader = base.ExecuteReader(command);
}
catch (System.Data.SqlClient.SqlException ex)
{
    throw new Exception("Oops! Something went wrong.");
}
Run Code Online (Sandbox Code Playgroud)

以下是我的存储过程:

SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [dbo].[usp_getBorrowerDetails]
    @BookID INT
AS
    SELECT 
        Name, Mobile, ReturnDate 
    FROM
        BorrowerDetails 
    INNER JOIN
        BookDetails ON BookDetails.CurrentBorrowerID = BorrowerDetails.ID    
    WHERE
        BookDetails.BookID = @BookID
GO
Run Code Online (Sandbox Code Playgroud)

如果我运行任何不需要任何参数的存储过程,它可以正常工作.只有在我添加参数时才会出现问题.

Rhu*_*orl 7

你重新定义command,以一个全新的SqlCommand设定之后CommandTypeCommandText,这意味着它将被视为纯SQL,而不是存储过程.在适当的位置创建一次.

IDataReader reader = null;
SqlCommand command;

try
{
    SqlConnection connection = GetDBConnection();

    command = new SqlCommand(Constants.SP_BookBorrowerDetails, connection);
    command.CommandType = CommandType.StoredProcedure;
    command.Parameters.AddWithValue("@BookID", bookID);

    reader = base.ExecuteReader(command);
}
catch (System.Data.SqlClient.SqlException ex)
{
    throw new Exception("Oops! Something went wrong.");
}
Run Code Online (Sandbox Code Playgroud)

顺便说一下,您可能还应该考虑不仅保持连接打开,而是在一个方法中获取结果,而不是依靠调用代码来管理连接.