针对SQL Server 2008运行Insert语句时失败



我必须部署在VB.NET和Visual Studio 2005中开发的VB.NET应用程序。客户使用的是SQL Server 2008,而应用程序是根据SQL Server 2000构建的。

我收到以下针对SQL Server 2008的错误:

"Outgoing_Invoice"表中标识列的显式值只能在使用列列表且identity Insert为ON 时指定

以下是我在两个表中插入数据的查询:

Dim cmd1 As New SqlCommand("Insert into Stock values(@invoice_no, @gate_pass, @exp_no, @clm_no, @category, @item_name, @weight, @units_case, 0, 0, @crtns_removed, @pieces_removed, 0, 0, @date_added, @date_removed, @inc_total_price, @out_total_price,  @discount, @amount, 'Sold', @expiry_date) Insert into Outgoing_Invoice values(@invoice_no, @exp_no, @party_name, @party_code, @city, @contact, @category, @item_name, @weight, @units_case, @crtns_issued, @pieces_issued, @crtns_removed, @pieces_removed, 0, 0, @scheme, @unit_price, @out_total_price, @discount, @amount, @date_removed, @expiry_date, @order_booker, @salesman)", con)

错误消息显示在cmd1.executenonquery。这两个表StockOutgoing_Invoice都有一个标识列,在@invoice之前标记为serial。

只有在SQL Server 2008上尝试插入时才出现此问题。当在SQL Server 2000上运行时,它可以按预期工作。

这个问题的可能原因是什么?如何解决?

您的INSERT查询需要在VALUES子句之前指定列名,否则将按照DB中定义的列顺序进行尝试(可能会发生更改-这是而不是固定的)。

由于出现错误,INSERT似乎试图插入到标识列中。

一般情况下,当不向所有列插入时,必须指定列名。我将始终指定列名作为最佳实践。

因此,指定一个列列表:

INSERT INTO aTable
(col1, col2)
VALUES
(@val1, @val2)

插入到Outgoing_Invoice中有一对多个参数。

这会很好用的。值1和2分别为C1和C2,ID自动分配。

declare @T table
(
  ID int identity,
  C1 int,
  C2 int
)
insert into @T values (1, 2)

这将给出的确切错误

insert into @T values (1, 2, 3)

请检查SQL Server 2000中的表结构。它可能有一个额外的字段。这可以解释为什么它在那里工作。

如果要修改/插入表的IDENTITY列值,则应显式指定字段列表。

Ie。您的查询应该是这样的:

Insert into Stock 
(
  here,
  comes,
  your,
  real,
  column,
  names
)
values
(
  @invoice_no, 
  @gate_pass, 
  @exp_no, 
  @clm_no, 
  @category, 
  @item_name, 
  @weight, 
  @units_case, 
  0, 
  0, 
  @crtns_removed, 
  @pieces_removed, 
  0, 
  0, 
  @date_added, 
  @date_removed, 
  @inc_total_price, 
  @out_total_price,  
  @discount, 
  @amount, 
  'Sold', 
  @expiry_date
) 
Insert into Outgoing_Invoice 
(
  here,
  comes,
  your,
  real,
  column,
  names,
  too
)
values
(
  @invoice_no, 
  @exp_no, 
  @party_name, 
  @party_code, 
  @city, 
  @contact, 
  @category, 
  @item_name, 
  @weight, 
  @units_case, 
  @crtns_issued, 
  @pieces_issued, 
  @crtns_removed, 
  @pieces_removed, 
  0, 
  0, 
  @scheme, 
  @unit_price, 
  @out_total_price, 
  @discount, 
  @amount, 
  @date_removed, 
  @expiry_date, 
  @order_booker, 
  @salesman
)

最新更新