In the C# code below, I'm having trouble when I try to use a bind variable
for the column name in an update command. The example below works fine when
I use the first sqlstr spelling out the column name. When I try to use the
second sqlstr using @columnName I get an error saying string or binary data
would be truncated. Below the code I have also pasted the command as sql
profiler shows it. It looks ok to me.
Anyone know the cause?
thanks,
T
public static string UOrderField(string columnname, string value, int key)
{
SqlConnection conn = new
SqlConnection((string)HttpContext.Current.Session["VTDBConnectionString"]);
conn.Open();
int rowsAffected;
//string sqlstr = "update orders set problemdesc = @value where
(ordernumber = @key)";
string sqlstr = "update orders set @columnname = @value where
(ordernumber = @key)";
SqlCommand cmd = new SqlCommand(sqlstr, conn);
cmd.Parameters.Add(new SqlParameter("@columnname", columnname));
cmd.Parameters.Add(new SqlParameter("@key", key));
cmd.Parameters.Add(new SqlParameter("@value", value));
try
{
rowsAffected = cmd.ExecuteNonQuery();
if (rowsAffected == 0)
{
return "Zero user emails were changed";
}
return "";
}
catch (Exception ex)
{
return ex.Message;
}
finally
{
conn.Close();
}
}
exec sp_executesql N'update orders set @columnname = @value where
(ordernumber = @key)',N'@columnname nvarchar(11),@key int,@value
nvarchar(12)',@columnname=N'problemdesc',@key=124063,@value=N'anothervalue'
Eric Isaacs - 30 Sep 2008 22:51 GMT
The sql isn't doing what you expect in that one case. It's just
assigning the nvarchar(12) @value to the nvarchar(11) @ColumnName, so
it's warning you that the data is being truncated to 11 characters.
You need to specify the field that is being updated in the sql
string. You can't pass a variable with this.
string sqlstr = "update orders set " + columnname + " = @value where
(ordernumber = @key)";
-Eric Isaacs