【问题标题】:Calling stored procedure with parameter to return list使用参数调用存储过程以返回列表
【发布时间】:2019-05-31 09:02:48
【问题描述】:

我有一个带参数的存储过程,我想在返回列表索引的视图中提交参数。我如何在我的控制器中解决这个问题

CREATE PROCEDURE [dbo].[spFlugReport]     
(      
   @AccNo INTEGER,
   @DateFrom DATE, 
   @DateTo DATE    
)      
AS
BEGIN
    SELECT * 
    FROM [dbo].[KIRData] 
    WHERE AccNo = @AccNo 
      AND StartDate >= @DateFrom 
      AND EndDate <= @DateTo 
      AND Prod = 'Air'
END

C#代码:

public ActionResult Report()
{
    using(DataModel db = new DataModel())
    {
        SqlParameter[] param = new SqlParameter[] {
            new SqlParameter("@AccNo ,"),
            new SqlParameter("@DateFrom ,"),
            new SqlParameter("@DateTo ,")
        };


    }
}

【问题讨论】:

  • 嗨,欢迎来到堆栈溢出。请问,你能更清楚地解释你想要什么吗?从你所说的,我无法理解你想要什么。
  • 我想将参数传递给我的存储过程以返回一个列表

标签: c# asp.net asp.net-mvc entity-framework


【解决方案1】:

欢迎堆栈溢出。这是一个有用的链接,可以帮助您实现您需要做的事情。

https://csharp-station.com/Tutorial/AdoDotNet/Lesson07

这里有一个与您的问题类似的问题How to execute a stored procedure within C# program

但是,这里有一个快速示例,说明您需要将参数传递给存储过程。

// create and open a connection object
SqlConnection conn = new SqlConnection("Server=(local);DataBase=Northwind;Integrated Security=SSPI");
conn.Open();

// 1.  create a command object identifying the stored procedure
SqlCommand cmd  = new SqlCommand("CustOrderHist", conn);

// 2. set the command object so it knows to execute a stored procedure
cmd.CommandType = CommandType.StoredProcedure;

// 3. add parameter to command, which will be passed to the stored procedure
cmd.Parameters.Add(new SqlParameter("@CustomerID", custId));

// execute the command
SqlDataReader rdr = cmd.ExecuteReader();

希望对你有所帮助。

【讨论】:

    【解决方案2】:

    我相信您正在寻找这样的东西。如果没有,您能否提供更多详细信息。

    DataTable database = new DataTable();
    string dbString = ConfigurationManager.ConnectionStrings["YourConnection"].ConnectionString;
    using (SqlConnection con = new SqlConnection(dbString))
    using (SqlCommand cmd = new SqlCommand("dbo.spFlugReport", con))
    {
        using(DataModel db = new DataModel())
        {
            cmd.CommandType = CommandType.StoredProcedure;
    
            cmd.Parameters.AddWithValue("@AccNo", AccNo);
            cmd.Parameters.AddWithValue("@DateFrom", DateFrom);
            cmd.Parameters.AddWithValue("@DateTo", DateTo);
    
            con.Open();
            cmd.ExecuteNonQuery();               
        }
    }
    

    此链接是您为 YourConnection 创建 ConnectionString 的方式:https://docs.microsoft.com/en-us/aspnet/mvc/overview/getting-started/introduction/creating-a-connection-string

    【讨论】:

      猜你喜欢
      • 2023-03-10
      • 1970-01-01
      • 2015-08-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多