【问题标题】:Passing Second Parameter to Stored Procedure in C#将第二个参数传递给 C# 中的存储过程
【发布时间】:2020-01-17 03:21:22
【问题描述】:

在下面的代码中,我试图检索经理的 ID,然后必须将其作为第二个参数传递给 SQL 存储过程,如下面的代码所示:

目前代码只使用一个参数(EmpID)。

 void EmpProfileLists(string EmpId,string EmpName)
    {
        if (EmpId == "0")
        {
            Label2.Text = "There is no Emp associated with your account";
            Label2.Visible = true;
        }
        else Label2.Visible = false;

        try
        {
        Session["EmpId"] = EmpId;
        Label1.Text = EmpId;

                if (Session["MgrName"] != null) Session.Remove("MgrName");

        var claimsIdentity = Context.Emp.Identity as ClaimsIdentity;

        foreach (var claim in claimsIdentity.Claims)
        {
            {
                Session.Add("MgrName", "micro\\"+Session["MgrName"].Substring(Session["MgrName"].LastIndexOf("/")));
            }
        }  
        string MgrName = Session["MgrName"].ToString();
        LoadProfiles(EmpId);
        }
        catch (Exception)
        {
      }
    }

    private void LoadProfiles(string EmpId)
        {
            try
            {
                SqlDataAdapter da = new SqlDataAdapter("Exec EmpReports " + EmpId); 
                DataTable dt = new DataTable();
                da.Fill(dt);
                RadGrid1.DataBind();
            }
            catch (Exception)
            {
            }
        }

代码在传递时仅适用于员工 ID,但我也在尝试添加经理 ID。

有人可以帮忙吗?

【问题讨论】:

  • Exec EmpReports " + EmpId, 请阅读 SQL 注入。
  • 而不是仅仅使用字符串来调用带有参数的过程,您应该使用SqlCommandParameters 集合,就像Dale 发现的问题一样。这可能会让人觉得冗长,但它避免了各种数据类型转换错误,并保护您免受 SQL 注入攻击。
  • 请分享存储过程的前5行。

标签: c# sql-server stored-procedures parameter-passing sqlcommand


【解决方案1】:
SqlCommand command = new SqlCommand("EmpReports", WebConfigurationManager.ConnectionStrings["EmpReportConnectionString"].ToString());
command.CommandType = CommandType.StoredProcedure;
command.Parameters.Add("@EmpId", SqlDbType.Int).Value = EmpId;
command.Parameters.Add("@ManId", SqlDbType.Int).Value = ManId;
command.ExecuteNonQuery();

【讨论】:

  • 谢谢斯特凡。我在代码部分的哪个位置检索 ManId 的值?
  • @Karu3103 你是说@ManIdoutput 参数吗?因为你的问题并不清楚。
  • 将此用于输出参数:command.Parameters.Add("@Result ", SqlDbType.Bit).Direction = ParameterDirection.Output;
  • 我不知道你想知道什么。您能否重新表述您的问题并指定检索 ManId 的位置以及您在存储过程中使用的输入和输出参数?
  • 嗨 Stefan,我已将存储过程添加为问题的一部分。 ManId 只不过是需要传递给存储过程的第二个参数的经理 ID。如果您查看 c# 代码中的第 23 行,它会告诉您 ManId 如何与“micro\\”结合使用。
猜你喜欢
  • 2011-07-22
  • 2011-07-21
  • 1970-01-01
  • 2016-04-05
  • 1970-01-01
相关资源
最近更新 更多