[英]Pass integer array to the SQL Server stored procedure
好吧,這個很好回答的問題,但是我無法解決。 我正在嘗試使用帶有某些參數的Entity Framework從.NET Core項目中調用存儲過程。 這些參數之一應該是數組(我通過創建自定義表數據類型來考慮SQL Server中的表類型)類型。 我遵循了這個Stackoverflow鏈接 。 但是當我嘗試執行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
他錯誤地使用了ExecuteSqlCommand。 他不應該使用字符串連接來避免應用程序中的SQL注入攻擊
_db.ExecuteSqlCommand(“ EXEC SP_GenerateRegularEmployeeSalary @YOUR_PARAM_ON_STOREPROCEDURE”,教員);
看起來您在錯誤地使用ExecuteSqlCommand
。 嘗試這種方式,不要在代碼中使用字符串連接,以避免應用程序中的SQL Injection攻擊。 在此處了解更多信息。
還要從存儲過程中輸入正確的預期參數名稱: 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);
請閱讀有關此方法的本文檔。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.