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 = amount
makes no sense: if you wanted to retrieve data using a parameter then you need to declare it, and if you wanted to retrieve usingExecuteScalar
then you would need justSELECT amount
.SELECT something
UPDATE something
just do the calculation in oneUPDATE
statement.for
loop 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
dt
must have exactly two columns in the correct order.