Identity column in a table-valued parameter in procedure, how to define DataTable

♀尐吖头ヾ 提交于 2019-12-10 18:33:46

问题


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?


回答1:


I had this same problem where we want an identity on the type, but don't want to provide a value. The key is to use a SqlMetaData constructor for that column that sets useServerDefault to true:

According to this article on using user defined table type with identify column in ado net by Tim Van Wassenhove

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)



回答2:


If the question is "how do I pass a TVP with a column marked INT IDENTITY(1,1)?" you don't. A TVP is not a table. You may be specifying the TVP values, which means that you don't want an identity on the value that you're supplying.

The table is usually the one that you want to have the IDENTITY declared on.

If the question is "How can I avoid setting the PK in the TVP?" then I would have to ask for more code.



来源:https://stackoverflow.com/questions/3210945/identity-column-in-a-table-valued-parameter-in-procedure-how-to-define-datatabl

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!