简体   繁体   English

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

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

I get an error when I input the drop down list parameter as data, I could not add the parameter data into the invoice table,the parameter data for subtotal, tax and total got their own value, but it only work well for manually input the data. 输入下拉列表参数作为数据时出现错误,我无法将参数数据添加到发票表中,小计,税金和总计的参数数据具有自己的值,但仅适用于手动输入数据。

Drop down list parameter: 下拉列表参数:

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();
}

Manually input: 手动输入:

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();
}

Just remove the field from your values-listing: 只需从您的值列表中删除该字段:

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

Also you can use the OUTPUT-Clause to get the value using: 您也可以使用OUTPUT-Clause通过以下方式获取值:

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

In the case you actually want to set the identity -column manually, you can use SET IDENTITY_INSERT as described here in MSDN 如果您实际上要手动设置identity列,则可以使用SET IDENTITY_INSERT ,如MSDN此处所述

不要设置发票ID

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

If you have it Incrementing in database you dont need to Alter it again in the code. 如果您在数据库中具有增量功能,则无需在代码中再次更改它。 Just remove the invoiceID from your statement 只需从您的对帐单中删除invoiceID

I'm not a .NET guy, but by googling I think you have to not mention the identity field in your insert query: 我不是.NET专家,但是通过谷歌搜索,我认为您不必在插入查询中提及标识字段:

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

Plz take a look in this simple tutorial: w3schools 请看这个简单的教程: 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