当我执行这个简单的插入查询时,为什么会出现此异常?

时间:2014-03-25 16:29:02

标签: c# asp.net .net sql-server sql-server-2012

我对此代码执行插入查询有问题(问题是当它尝试执行查询时抛出异常):

_strSQL = "INSERT INTO Cpe ( DateAdded,  [Cpe] ";
strSQLParametri = " VALUES ( GETDATE(), @CPE ";
addParameter(command, "@CPE ", cpe.Cpe);


// [SourceId] insertion on the DB:
if (cpe.SourceId != null)
{
                _strSQL += ",[SourceId] ";
                strSQLParametri += ", @SOURCEID ";
                addParameter(command, "@SOURCEID ", cpe.SourceId);
}

// [vendor_id] insertion on the DB:
if (cpe.VendorId != null)
{
                _strSQL += ",[vendor_id] ";
                strSQLParametri += ", @VENDORID ";
                addParameter(command, "@VENDORID ", cpe.VendorId);
}

// [Title] insertion on the DB:
if (cpe.Title != null)
{
                _strSQL += ",[Title] ";
                strSQLParametri += ", @TITLE ";
                addParameter(command, "@TITLE ", cpe.Title);
}

// [part] insertion on the DB:
if (cpe.Part != null)
{
                _strSQL += ",[part] ";
                strSQLParametri += ", @PART ";
                addParameter(command, "@PART ", cpe.Part.ToString());
}

// [product_id] insertion on the DB:
if (cpe.ProductId != null)
{
                _strSQL += ",[product_id] ";
                strSQLParametri += ", @PRODUCTID";
                addParameter(command, "@PRODUCTID ", cpe.ProductId);
}

// [version] insertion on the DB:
if (cpe.Version != null)
{
                _strSQL += ",[version] ";
                strSQLParametri += ", @VERSION";
                addParameter(command, "@VERSION ", cpe.Version);
}

// [revision] insertion on the DB:
if (cpe.Revision != null)
{
               _strSQL += ",[revision] ";
                strSQLParametri += ", @REVISION";
                addParameter(command, "@REVISION ", cpe.Revision);
}

// [edition] insertion on the DB:
if (cpe.Edition != null)
{
                _strSQL += ",[edition] ";
                strSQLParametri += ", @EDITION";
                addParameter(command, "@EDITION ", cpe.Edition);
}

.... and so on ......

query = _strSQL + " ) " + strSQLParametri + " );";
command.CommandText = query;
_executeNoQuery(command);

newId = _getIdentity();
//Debug.WriteLine("Id: " + newId);
#endregion

这是获取的查询,请参阅调试器托架的内容(之前没有所有字段,因为有人为空,因此会跳过它们):

INSERT INTO Cpe (DateAdded, [Cpe], [SourceId], [vendor_id], [Title], [part], [product_id], [version])  
VALUES (GETDATE(), @CPE, @SOURCEID, @VENDORID, @TITLE, @PART, @PRODUCTID, @VERSION);

这是在执行上一个查询时发生的获取异常:

  

ExecuteNonQuery terminato con errori。 \ r \ nINSINS INTO Cpe(DateAdded,[Cpe],[SourceId],[vendor_id],[Title],[part],[product_id],[version])VALUES(GETDATE(),@ CPE,@ SOURCEID,@ VENDORID,@ TITLE,@ PART,@ PRODUCOR,@ VERSION);
  字符串或二进制数据将被截断。

可能是什么问题?你对我怎么解决了吗?

2 个答案:

答案 0 :(得分:2)

错误消息String or binary data would be truncated.的这一部分表明您尝试将数据插入到太小的字段中。

检查您要插入的任何文字数据的长度,然后检查您尝试插入的字段的大小,确保其适合。

答案 1 :(得分:0)

检查传入的每个字符串值的长度。其中一个几乎肯定比插入数据的列的长度长。