2012-01-28 56 views
0

我必須部署在VB.NET和Visual Studio 2005中開發的VB.NET應用程序。客戶正在使用SQL Server 2008,而應用程序是針對SQL Server 2000構建的。在針對SQL Server 2008運行時插入語句失敗

我收到針對SQL Server 2008中的以下錯誤:

當使用列列表只能被指定爲「Outgoing_Invoice」標識列一個明確的價值和身份插入接通

這裏是我的兩個表中插入數據查詢:

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運行時,它按預期工作。

這個問題可能的原因是什麼?如何解決?

回答

4

INSERT查詢需要的VALUES條款,否則它們將嘗試在列順序在DB定義之前指定的列名(這是受改變 - 這是固定)。

由於您收到錯誤,因此INSERT嘗試插入到標識列中。

一般 - 如果不插入到所有列,你必須指定列名。我會總是指定列名稱作爲最佳實踐。

所以 - 指定列的列表:

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

@ user944591 - 您不能依賴訂購(答案已更新)。當不插入_all_列時,您必須**指定列名稱。 – Oded 2012-01-28 20:55:08

2

插入到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中它可能有一個額外的領域。這將解釋爲什麼它在那裏工作。

0

如果要修改/插入表的IDENTITY列值,應明確指定字段列表。

即,您的查詢應如下所示:

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 
)