Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to execute stored procedure with Output parameters using FromSqlInterpolated/Database.ExecuteSqlInterpolated in Dot Net Core 3.1?

I would like to execute a stored procedure with output parameter in Dot Net core 3.1. I am using the ExecuteSqlInterpolated extension method of a DatabaseFacade class.

C# code to get employee's count.

string deptName="IT";
int? employeeCount = null;
Database.ExecuteSqlInterpolated($"exec dbo.usp_GetEmpCountByDept {deptName}, {employeeCount} out");

After execution employeeCount is null and -1 is the return value. As some people requested stored proc code for reproducing the issue ,I have stored proc as below

CREATE PROCEDURE usp_GetEmpCountByDept
@Dept nvarchar(20),
@EmpCount int Output
AS
BEGIN
SELECT @EmpCount = COUNT(Id)
FROM [dbo].[Employees] 
WHERE Department = @Dept
END
like image 566
Vishal P Avatar asked Jan 21 '20 09:01

Vishal P


2 Answers

I have found other way which is working for me

  1. Add Nuget package Microsoft.Data.SqlClient

  2. Use ExecuteSqlRaw method instead

Below is the code

    int? employeeCount = null;
    string deptName="IT";

    // Use Microsoft.Data.SqlClient namespace for SqlParameter.Visual studio will suggest  "system.data.sqlclient" which does not work
    var deptNameSQLParam = new Microsoft.Data.SqlClient.SqlParameter("@Dept", deptName);
    var employeeCountSQLParam = new Microsoft.Data.SqlClient.SqlParameter("@EmpCount", SqlDbType.Int) { Direction = ParameterDirection.Output }; 
    Database.ExecuteSqlRaw("exec dbo.usp_GetEmpCountByDept @Dept={0}, @EmpCount={1} out", deptNameSQLParam, employeeCountSQLParam);

     if (employeeCountSQLParam.Value != DBNull.Value)
     {
        employeeCount = (int)employeeCountSQLParam.Value;
     }
like image 52
Vishal P Avatar answered Nov 10 '22 12:11

Vishal P


change this

string deptName="IT";
int? employeeCount = null;
Database.ExecuteSqlInterpolated($"exec dbo.usp_GetEmpCountByDept {deptName}, {employeeCount} out");

to this (worked for me with .NET 5, don't know about earlier)

string deptName="IT";

// make explicit SQL Parameter
var output = new SqlParameter("@EmployeeCount", SqlDbType.Int) { Direction = ParameterDirection.Output };

// use output parameter instead
Database.ExecuteSqlInterpolated($"exec dbo.usp_GetEmpCountByDept {deptName}, {output} out");

// assign output
int? employeeCount = output.Value;
like image 33
r3mark Avatar answered Nov 10 '22 14:11

r3mark