我有此表类型
CREATE TYPE ItemTableType AS TABLE
(
BrandId INT,
BranchId INT,
InventoryCategoryId INT,
Attributes nvarchar(Max),
Price Decimal(18,2),
[Description] nvarchar(Max)
);
我用这样的C#代码创建一个数据表
var dt = new DataTable();
dt.Columns.Add("BrandId");
dt.Columns.Add("BranchId");
dt.Columns.Add("attributes");
dt.Columns.Add("InventoryCategoryId");
dt.Columns.Add("Price");
dt.Columns.Add("Description");
foreach (var item in inventoryItems)
{
DataRow r = dt.NewRow();
r["BrandId"] = item.BrandId;
r["BranchId"] = item.BranchId;
r["InventoryCategoryId"] = item.InventoryCategoryId;
r["attributes"] = item.Attributes;
r["Price"] = item.Price;
r["Description"] = item.Description;
dt.Rows.Add(r);
}
当我尝试将dt传递到SP中时,我会得到
{System.Data.SqlClient.SqlException (0x80131904): Conversion failed when converting the nvarchar value '{"PartNumber":"XA1167","Qty":999,"CleanedPartNumber":"1167"}' to data type int.
The data for table-valued parameter "@Source" doesn't conform to the table type of the parameter. SQL Server error is: 245, state: 1
The statement has been terminated.
at System.Data.SqlClient.SqlConnection.OnError(SqlException exception, Boolean breakConnection, Action`1 wrapCloseInAction)
at System.Data.SqlClient.SqlInternalConnection.OnError(SqlException exception, Boolean breakConnection, Action`1 wrapCloseInAction)
at System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject stateObj, Boolean callerHasConnectionLock, Boolean asyncClose)
at System.Data.SqlClient.TdsParser.TryRun(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataReader dataStream, BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject stateObj, Boolean& dataReady)
at System.Data.SqlClient.SqlCommand.FinishExecuteReader(SqlDataReader ds, RunBehavior runBehavior, String resetOptionsString)
at System.Data.SqlClient.SqlCommand.RunExecuteReaderTds(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, Boolean async, Int32 timeout, Task& task, Boolean asyncWrite, SqlDataReader ds)
at System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, TaskCompletionSource`1 completion, Int32 timeout, Task& task, Boolean asyncWrite, String method)
at System.Data.SqlClient.SqlCommand.InternalExecuteNonQuery(TaskCompletionSource`1 completion, Boolean sendToPipe, Int32 timeout, Boolean asyncWrite, String methodName)
at System.Data.SqlClient.SqlCommand.ExecuteNonQuery()
at line 202
ClientConnectionId:7a91a363-e5a0-4476-a92f-d02c30262728
Error Number:245,State:1,Class:16}
为什么会在什么时候认为它是Int?
答案 0 :(得分:3)
很明显,您创建的类型InventoryCategory
的第三列是Int
,而数据表的第三列是varchar
。您必须重新排列数据表中的列。
添加列时使用:
dt.Columns.Add("InventoryCategoryId");
dt.Columns.Add("attributes");