简体   繁体   中英

How can I use ExecuteScalar to check if a record exists using 2 variables such as product ID and color?

SqlConnection BagleyData1 = new SqlConnection(ConfigurationManager.ConnectionStrings["BagleyInvetory_VBConnectionString"].ConnectionString);
BagleyData1.Open();

SqlCommand check_productSku = new SqlCommand("SELECT COUNT(*) FROM [dbo].[product_subtract_inventory] WHERE ([inv_prodID] = @inv_prodID) AND ([inv_color] = @inv_color)", BagleyData1);
check_productSku.Parameters.AddWithValue("@inv_prodID", Request.QueryString["ProdID"]);
int SkuExist = (int)check_productSku.ExecuteScalar();
BagleyData1.Close();
if (SkuExist > 0)
{
    **exists
}
else
{
   **doesn't exist
}

The only major problem I see in that code is you forgot to add a line to set the value for the @inv_color parameter. Try adding a line like:

check_productSku.Parameters.AddWithValue("@inv_color", Request.QueryString["Color"]);

before you execute. Your query has two @parameters so your c# code should have two lines like command.Parameters.AddWithValue(...) , one for each parameter

Naturally you'll have to replace Request.QueryString["Color"] with the actual value you want to supply to the query

Side note; some bathroom reading material for you: https://blogs.msmvps.com/jcoehoorn/blog/2014/05/12/can-we-stop-using-addwithvalue-already/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM