如何编写自动生成 ID 的查询

How to write the query for auto-generated ID

当我输入下拉列表参数作为数据时出现错误,我无法将参数数据添加到发票中table,小计、税金和总计的参数数据有它们自己的值,但它只适用于手动输入数据。

下拉列表参数:

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 列,您可以按照 here in MSDN

所述使用 SET IDENTITY_INSERT

不要设置发票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;