【问题标题】:Pass integer array to the SQL Server stored procedure将整数数组传递给 SQL Server 存储过程
【发布时间】:2019-06-08 15:20:47
【问题描述】:

这个问题得到了很好的回答,但我无法正确回答。我正在尝试使用带有一些参数的实体框架从 .NET Core 项目调用存储过程。其中一个参数应该是数组(我通过创建自定义表数据类型来考虑 SQL Server 中的表类型)类型。我关注了this Stackoverflow link。但是当我尝试执行我的 SQL 命令时出现错误。

这是我的代码:

DataTable dt = new DataTable();
dt.Columns.Add("ID", typeof(int));

foreach (var section in model.VMSectionIds) //model.VMSectionIds contains set of integers
{
    dt.Rows.Add(section);
}

最后我这样调用存储过程:

var sectiolist = new SqlParameter("@Sections", SqlDbType.Structured)
            {
                TypeName = "[dbo].[SectionList]",
                Value = dt
            };
_db.ExecuteSqlCommand("EXEC [SP_GenerateRegularEmployeeSalary] "+mastermodel.ID+","+ fromdate + "," + todate + ",1," + sectiolist + ""); //don't worry I took care of SQL injection for others parameter

但是这个执行抛出异常

SqlException:必须声明标量变量“@Sections”

我无法弄清楚确切的问题出在哪里。这里从 SQL 调用存储过程(带有一些静态测试参数),以便清楚地了解我的存储过程调用机制:

DECLARE @data [SectionList]
INSERT @data (Id) VALUES (2, 3)

EXEC [SP_GenerateRegularEmployeeSalary] 2,'20190401','20190430','1',@data

【问题讨论】:

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


【解决方案1】:

您似乎错误地使用了ExecuteSqlCommand。尝试这种方式,不要在代码中使用字符串连接,以避免应用程序中的 SQL 注入攻击。阅读更多关于它的信息here

还要从存储过程中输入正确的预期参数名称:SP_GenerateRegularEmployeeSalary

选项 1

_db.ExecuteSqlCommand("EXEC [SP_GenerateRegularEmployeeSalary] @ID, @FromDate, @ToDate, @Flag, @Sections", 
   new SqlParameter("@ID", mastermodel.ID),
   new SqlParameter("@FromDate", fromdate),
   new SqlParameter("@ToDate", todate),
   new SqlParameter("@Flag", 1),
   new SqlParameter("@Sections", sectiolist));

选项 2

_db.ExecuteSqlCommand("EXEC [SP_GenerateRegularEmployeeSalary] @ID = {0}, @FromDate = {1}, @ToDate = {2}, @Flag = 1, @Sections = {4}", mastermodel.ID, fromdate, todate, sectiolist);

请阅读this有关此方法的文档。

【讨论】:

    【解决方案2】:

    他错误地使用了 ExecuteSqlCommand。他不应该使用字符串连接来避免应用程序中的 SQL 注入攻击

    _db.ExecuteSqlCommand("EXEC SP_GenerateRegularEmployeeSalary @YOUR_PARAM_ON_STOREPROCEDURE", sectiolist);

    【讨论】:

    • 任何解释这种方法的不同之处,以及为什么这可以解决问题?
    • 他错误地使用了 ExecuteSqlCommand。他不应该使用字符串连接来避免应用程序中的 SQL 注入攻击
    • 把这个解释放在你的答案中! (我完全同意,顺便说一句)
    • 谢谢,我现在知道了,但我只能提供一个作为正确答案,希望您能提供一点解释和答案以使其被接受。 :)
    猜你喜欢
    • 2014-08-29
    • 1970-01-01
    • 1970-01-01
    • 2015-12-20
    • 2013-07-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-02-19
    相关资源
    最近更新 更多