I am currently getting this error code when trying to execute an insert query in C#
System.Data.SqlClient.SqlException: 'Subquery returned more than 1 value. This is not permitted when the subquery follows =, !=, <, <= , >, >= or when the subquery is used as an expression.
The statement has been terminated.'
I am trying to insert user entered values into a table, then return the ID from the primary key of that table, then insert values into a different table and insert the returned ID into the foreign key into this table.
Here is my C# code from when the button to submit the values is pressed:
protected void btnSubmit_Click(object sender, EventArgs e)
{
string query = "insert into Stock_Take(Username, StockDate) OUTPUT INSERTED.StockTakeIDNew values(@Username, GetDate()); Insert into Stock_Take_Item(ItemID, BarQuantity, StorageQuantity, StockTakeIDNew) values(@ID, @BAR, @STORAGE, (Select StockTakeIDNew from Stock_Take))";
SqlConnection con = new SqlConnection(connectionString);
SqlCommand cmd = new SqlCommand(query, con);
con.Open();
foreach (GridViewRow row in gvStockTake.Rows)
{
Label ID = row.FindControl("itemId") as Label;
TextBox BAR = row.FindControl("txtBar") as TextBox;
TextBox STORAGE = row.FindControl("txtStorage") as TextBox;
cmd.Parameters.Clear();
cmd.Parameters.Add("@ID", SqlDbType.VarChar).Value = ID.Text;
cmd.Parameters.Add("@BAR", SqlDbType.Int).Value = BAR.Text;
cmd.Parameters.Add("@STORAGE", SqlDbType.Int).Value = STORAGE.Text;
}
cmd.Parameters.AddWithValue("@Username", Session["username"]);
cmd.ExecuteNonQuery();
con.Close();
Response.Write("Successfully inserted stock take items.");
}
What I have tried:
I think that perhaps I should split the query into two, and have a query1 for the second half of the SQL statement. Therefore executing the first first half of the query first, and then the second half once i had added the parameters in the 'foreach' section?
I'm still new to C# and SQL so any recommendations are fully appreciated!!