SQL Server How to declare scalar variable in parameterized method in ASP.NET Core?

dpiehjr4  于 2023-11-16  发布在  Scala
关注(0)|答案(1)|浏览(105)

I want to get value by using parameterized method, but l am getting this error
Must declare the scalar variable @Category

I don't know where and how to declare the scalar variable in the code below.

See the code that I have tried

[Route("TotalValue")]
[HttpGet]
public decimal TotalValue()
{
    var query = "Select * from OrderDetail where Category = @Category";
    string sqlDataSource = _configuration.GetConnectionString("DefaultConnection");
    decimal total = 0;

    using (SqlConnection con = new SqlConnection(sqlDataSource))
    {
        con.Open();

        using (SqlCommand cmd = new SqlCommand(query, con))
        {
            using (SqlDataReader dr = cmd.ExecuteReader())
            {
                if (dr.Read())
                {
                    total = dr.GetDecimal(0); 
                }
            }
        }

        con.Close();
    }

    return total;
}
szqfcxe2

szqfcxe21#

You're almost there.

After creating the command, add the @Category parameter to the command's parameters collection:

[Route("TotalValue")]
[HttpGet]
public decimal TotalValue()
{
    var query = "Select * from OrderDetail where Category = @Category";
    string sqlDataSource = _configuration.GetConnectionString("DefaultConnection");
    decimal total = 0;

    // If a string (amend for other data type)
    string categoryToFind = "My Category To Search For";

    using (SqlConnection con = new SqlConnection(sqlDataSource))
    {
        con.Open();
        using (SqlCommand cmd = new SqlCommand(query, con))
        {
            cmd.Parameters.AddWithValue("@Category", categoryToFind);

            using (SqlDataReader dr = cmd.ExecuteReader())
            {
                if (dr.Read())
                {
                    total = dr.GetDecimal(0); 
                }
            }
        }
        con.Close();
    }

    return total;
}

相关问题