4

Is it possible to pass a parameter of type "table" with a column of type "[int] IDENTITY(1,1)" to a procedure and execute this stored procedure with a DataTable object passed as the input parameter?

I get the following error: "INSERT into an identity column not allowed on table variables. The data for table-valued parameter \"@xxxxx\" doesn't conform to the table type of the parameter."

The only related comment I was able to find was "If you supply a value for an identity column in a table-valued parameter, you must issue the SET IDENTITY_INSERT statement for the session."

It seems that even though the PK was not set in the table parameter, it gets set automatically at some point. Where does that happen and how can it be avoided?

4

2 回答 2

7

我有同样的问题,我们想要一个类型的标识,但不想提供一个值。关键是使用SqlMetaData该列的构造函数设置useServerDefaulttrue

根据Tim Van Wassenhove在 ado 网络中使用用户定义的表类型和识别列的这篇文章

SQL

CREATE TYPE [Star].[example] AS TABLE(  
  [Ordinal] [int] IDENTITY(1,1) NOT NULL,  
  [Name] [nvarchar](200) NOT NULL,
)

C#

var sqlMetaData = new[] 
{  
  new SqlMetaData("Ordinal", SqlDbType.Int, true, false, SortOrder.Unspecified, -1),   
  new SqlMetaData("Name", SqlDbType.NVarChar, 200)
};

sqlRecords = new HashSet<SqlDataRecord>(usersToInclude.Select(user =>
{   
  var record = new SqlDataRecord(sqlMetaData);   
  record.SetString(1, user.Name);   
  return record; 
}));

new SqlMetaData("IdentityField", SqlDbType.Int, true, false, SortOrder.Unspecified, -1)
于 2012-04-17T14:53:34.193 回答
1

如果问题是“我如何传递带有标记为 INT IDENTITY(1,1) 的列的 TVP?” 你没有。TVP 不是一张桌子。您可能正在指定 TVP 值,这意味着您不希望提供的值具有标识。

该表通常是您希望在其上声明 IDENTITY 的表。

如果问题是“如何避免在 TVP 中设置 PK?” 那么我将不得不要求更多的代码。

于 2011-03-18T14:57:27.373 回答