我从大型Excel工作表导入数据并将其存储在stateTable中。现在我必须将此数据推送到数据库表中。该表有一个标识列(1,1)。
我在DB中创建了一个类似的表类型,以及一个将参数作为表类型插入到特定表中的过程。我也设置了身份插入。
我的代码是:
using (SqlCommand command = new SqlCommand("InsertStateTable") {
CommandType = CommandType.StoredProcedure})
{
SqlParameter param = command.Parameters.AddWithValue("@statetable", dt);
param.TypeName = "StateTable";
param.SqlDbType = SqlDbType.Structured;
command.Connection = con;
con.Open();
command.ExecuteNonQuery();
con.Close();
}
但出现的错误是 “INSERT到表变量上不允许进入标识列。” 我已经通过许多网站,但没有给出具体原因.....
提前致谢。
答案 0 :(得分:1)
错误相当明确:不允许你做你想做的事。基本上,您将不得不找到一个不依赖于将标识值插入table-variable / table-valued-parameter的设计。我的建议是创建一个单独的表变量(与表值参数无关),它具有相同的数据,但没有IDENTITY
列,所以..
declare @foo table (id int not null, name nvarchar(200) not null /* etc */)
insert @foo (id, name /* etc */)
select id, name /* etc */ from @statetable
此时@foo
包含原始数据,但没有标识列 - 然后您可以使用@foo
执行任何操作。
如果没有看到您使用身份插入执行的操作,则很难进一步发表评论。