字符串或二进制数据将被截断。

时间:2012-08-20 12:42:31

标签: c# sql-server

我正在C#网络应用中构建输入表单。我可以提交它,但我收到System.Data.SqlClient.SqlException (0x80131904): String or binary data would be truncated错误。我知道它有一个长度问题,但我已经仔细检查了一切,但似乎无法在这里弄明白。

{
    // Open Connection
    thisConnection.Open();

    // Create INSERT statement with named parameters
    nonqueryCommand.CommandText = "INSERT  INTO InventoryInput (Date, Item, Qty, WStatus) VALUES (@Date, @Qty, @Item, @WStatus)";


    // Add Parameters to Command Parameters collection
    nonqueryCommand.Parameters.Add("@Date", System.Data.SqlDbType.DateTime);
    nonqueryCommand.Parameters.Add("@Item", System.Data.SqlDbType.VarChar, 255);
    nonqueryCommand.Parameters.Add("@QTY", System.Data.SqlDbType.NChar, 10);
    nonqueryCommand.Parameters.Add("@WStatus", System.Data.SqlDbType.VarChar, 50);


    nonqueryCommand.Parameters["@Date"].Value = TextBox1.Text;
    nonqueryCommand.Parameters["@Item"].Value = DropDownList1.Text;
    nonqueryCommand.Parameters["@QTY"].Value = TextBox2.Text;
    nonqueryCommand.Parameters["@WStatus"].Value = DropDownList3.Text;
    nonqueryCommand.ExecuteNonQuery();

}

enter image description here

2 个答案:

答案 0 :(得分:7)

你混淆了两个专栏:

(Date,  Item, Qty,   WStatus) VALUES
(@Date, @Qty, @Item, @WStatus)

您尝试将@Qty插入Item列(好),将@Item插入Qty列(可能是错误的)。

我也同意一些数据类型仍然可疑的评论 - 例如非数字数量。

答案 1 :(得分:2)

使用Substring()确保您的输入不会太长:

nonqueryCommand.Parameters["@Date"].Value = TextBox1.Text;
nonqueryCommand.Parameters["@Item"].Value = DropDownList1.Text.Substring(0, 255);
nonqueryCommand.Parameters["@QTY"].Value = TextBox2.Text.Substring(0, 10);
nonqueryCommand.Parameters["@WStatus"].Value = DropDownList3.Text.Substring(0, 50);
相关问题