I have a piece of code which deletes and inserts a record into a table. The INSERT though always fails with the message "string or binary data would be truncated".
I do know that this error is typically caused by trying to write a string that's longer than the column's maximum length. But the strange thing is, that the same query works correctly when I execute it "manually" through SQL Server Management Studio.
Here's my table:
CREATE TABLE [dbo].[a_settings](
[a_setting_name] [nvarchar](30) NOT NULL,
[a_setting_value] [nvarchar](80) NULL
)
and the query I am using:
DELETE FROM [a_settings] WHERE [a_setting_name] = 'x1';
INSERT INTO [a_settings] ([a_setting_name], [a_setting_value])
VALUES ('x1', '0000000000000000000000000000000000000000');
and the C# code I am using:
SqlCommand cmd =
new SqlCommand(
String.Format(@"
DELETE FROM [{0}] WHERE [a_setting_name] = @setting_name;
INSERT INTO [{0}] ([a_setting_name], [a_setting_value]) VALUES (@setting_name, @setting_value)",
TBL_SETTINGS),
Connection);
cmd.Parameters.Add(new SqlParameter("setting_name", "x1"));
cmd.Parameters.Add(new SqlParameter("setting_value", "0000000000000000000000000000000000000000"));
cmd.ExecuteNonQuery();
Without making you have to count them: there are 40 zeroes.
The thing is: if I reduce the number of zeroes to something like 30, it works. But with 40 I get the "string or binary data would be truncated". In SSMS though, it works either way.
EDIT: Initially I used this code instead of the one shown above with SQL-Parameters
SqlCommand cmd =
new SqlCommand(
String.Format(@"
DELETE FROM [{0}] WHERE [a_setting_name] = '{1}';
INSERT INTO [{0}] ([a_setting_name], [a_setting_value]) VALUES ('{1}', '{2}')",
TBL_SETTINGS, 'x1', '0000000000000000000000000000000000000000'),
Connection);
cmd.ExecuteNonQuery();
And I then placed a breakpoint, copied the value of cmd.CommandText and pasted it right into SMSS (removing the \r and \t chars) and ran the query: it worked. In C# it did not.
@at the start of the parameter name? Also, you can explicitly give the SqlDbType for the parameter type and its size.nvarchar(80)I would not expect to get an error when adding 40 characters.