簡體   English   中英

如何編寫自動生成的ID的查詢

[英]How to write the query for auto-generated ID

輸入下拉列表參數作為數據時出現錯誤,我無法將參數數據添加到發票表中,小計,稅金和總計的參數數據具有自己的值,但僅適用於手動輸入數據。

下拉列表參數:

using (var cmd = con.CreateCommand())
{
cmd.CommandText = @"insert into Invoice(subtotal,tax,total) values (@subtotal,@tax,@total); select SCOPE_IDENTITY() as invoiceID;";
cmd.Parameters.AddWithValue("@subtotal", subtotal);
cmd.Parameters.AddWithValue("@tax", tax);
cmd.Parameters.AddWithValue("@total", total);
object OBJinvoiceID = cmd.ExecuteScalar();
}

手動輸入:

using (var cmd = con.CreateCommand())
{
cmd.CommandText = @"insert into Invoice(subtotal,tax,total) values (2,2,2); select SCOPE_IDENTITY() as invoiceID;";
object OBJinvoiceID = cmd.ExecuteScalar();
}

只需從您的值列表中刪除該字段:

insert into Invoice(subtotal,tax,total) values (@subtotal,@tax,@total); select SCOPE_IDENTITY() as invoiceID;

您也可以使用OUTPUT-Clause通過以下方式獲取值:

into Invoice(subtotal,tax,total) OUTPUT invoiceID values (@subtotal,@tax,@total);

如果您實際上要手動設置identity列,則可以使用SET IDENTITY_INSERT ,如MSDN此處所述

不要設置發票ID

insert into Invoice(subtotal,tax,total) values (@subtotal,@tax,@total);

如果您在數據庫中具有增量功能,則無需在代碼中再次更改它。 只需從您的對帳單中刪除invoiceID

我不是.NET專家,但是通過谷歌搜索,我認為您不必在插入查詢中提及標識字段:

using (var cmd = con.CreateCommand())
            {
                cmd.CommandText = @"insert into Invoice(subtotal,tax,total) values (@subtotal,@tax,@total);
// the rest
            }

請看這個簡單的教程: w3schools

insert into Invoice(subtotal,tax,total) values (@subtotal,@tax,@total); select SCOPE_IDENTITY() as invoiceID;

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM