the error that I'm getting is " Must declare the scalar variable "@x"."
I'm trying to declare a variable @x and make him a NVARCHAR(50)
then id like to subtract an amount from it called @z
and finally update a Table in the server called Stock with the out come of @x -@z
cmd.CommandText = "DECLARE @x AS NVARCHAR(50)";
cmd.ExecuteScalar();
for(int i=0;i<length;i++)
{
for(int j=0;j<2;j++)
{
//for ease of use
string name = dt.Rows[i][0].ToString();
string amount = dt.Rows[i][1].ToString();
cmd.CommandText = "SELECT @x = amount FROM Stock WHERE name = '"+name +"'";
cmd.ExecuteScalar();// im getting the error here but assume it will be in every executescalar
Thread.Sleep(100);
Console.WriteLine("end update");
cmd.CommandText = "DECLARE @z AS integer";
cmd.ExecuteScalar();
Thread.Sleep(100);
Console.WriteLine("end update");
cmd.CommandText = "SELECT @z = " + amount;
cmd.ExecuteScalar();
Thread.Sleep(100);
Console.WriteLine("end update");
cmd.CommandText = "UPDATE stock SET amount = @x -@z WHERE name='" + name + "'";
cmd.ExecuteScalar();
Thread.Sleep(100);
Console.WriteLine("end update");
}
}
dt rows is fine and does give appropriate values
You have a number of issues with your code:
SELECT @x = amountmakes no sense: if you wanted to retrieve data using a parameter then you need to declare it, and if you wanted to retrieve usingExecuteScalarthen you would need justSELECT amount.SELECT somethingUPDATE somethingjust do the calculation in oneUPDATEstatement.forloop is supposed to do, it's just doing the same thing three times.Thread.Sleep?So your code becomes:
However, this is still going to be slow for a large number of rows. It will be more efficient to use a Table-Valued Parameter to do the whole update in bulk.
First, create a Table Type. I usually have a few standard ones, for example a two-column one of strings and decimals:
Then you can use it like this:
The value
dtmust have exactly two columns in the correct order.